哲学家就餐问题:
public class Zhexuejia
{
private static final int MANNUM = 5;
public static void main(String[] args)
{
Kuaizi kz = new Kuaizi();
for(int loop = 0; loop < MANNUM; loop++)
{
new Man(loop, kz).start();
}
}
}class Kuaizi
{
//筷子标记,ture:可用 false:不可用
public boolean[] k;
//筷子数
private final int NUM = 5;
public Kuaizi()
{
//初始化,筷子可用
k = new boolean[NUM];
for(int loop = 0; loop < k.length; loop++)
{
k[loop] = true;
}
}
public synchronized void get(int ZhexuejiaNo)
{
while((!k[ZhexuejiaNo%NUM]) || (!k[(ZhexuejiaNo + NUM - 1)%NUM]))
{
try
{
this.wait();
} catch (InterruptedException e) { }
}
k[ZhexuejiaNo%NUM] = false;
k[(ZhexuejiaNo + NUM - 1)%NUM] = false;
}
public synchronized void put(int ZhexuejiaNo)
{
k[ZhexuejiaNo%NUM] = true;
k[(ZhexuejiaNo + NUM - 1)%NUM] = true;
this.notify();
}
}class Man extends Thread
{
private int number;
private Kuaizi kuaizi;
public Man(int num, Kuaizi kuaizi)
{
this.number = num;
this.kuaizi = kuaizi;
}
public void run ()
{
//System.out.println(number + " thread start ");
kuaizi.get(number);
System.out.println(number + " eat... ");
try
{
sleep(100);
}
catch(InterruptedException e)
{
}
System.out.println(number + " eated ");
kuaizi.put(number);
//System.out.println(number + " thread end ");
}
}
public class Zhexuejia
{
private static final int MANNUM = 5;
public static void main(String[] args)
{
Kuaizi kz = new Kuaizi();
for(int loop = 0; loop < MANNUM; loop++)
{
new Man(loop, kz).start();
}
}
}class Kuaizi
{
//筷子标记,ture:可用 false:不可用
public boolean[] k;
//筷子数
private final int NUM = 5;
public Kuaizi()
{
//初始化,筷子可用
k = new boolean[NUM];
for(int loop = 0; loop < k.length; loop++)
{
k[loop] = true;
}
}
public synchronized void get(int ZhexuejiaNo)
{
while((!k[ZhexuejiaNo%NUM]) || (!k[(ZhexuejiaNo + NUM - 1)%NUM]))
{
try
{
this.wait();
} catch (InterruptedException e) { }
}
k[ZhexuejiaNo%NUM] = false;
k[(ZhexuejiaNo + NUM - 1)%NUM] = false;
}
public synchronized void put(int ZhexuejiaNo)
{
k[ZhexuejiaNo%NUM] = true;
k[(ZhexuejiaNo + NUM - 1)%NUM] = true;
this.notify();
}
}class Man extends Thread
{
private int number;
private Kuaizi kuaizi;
public Man(int num, Kuaizi kuaizi)
{
this.number = num;
this.kuaizi = kuaizi;
}
public void run ()
{
//System.out.println(number + " thread start ");
kuaizi.get(number);
System.out.println(number + " eat... ");
try
{
sleep(100);
}
catch(InterruptedException e)
{
}
System.out.println(number + " eated ");
kuaizi.put(number);
//System.out.println(number + " thread end ");
}
}
import java.io.*;
import mailserver.common.utils.Logger;public class SMTPServerListener extends Thread
{
public SMTPServerListener()
{
} public static void main(String[] args)
{
SMTPServerListener SMTPServerListener1=new SMTPServerListener();
} public void run()
{
Logger log=new Logger(this.getClass());//用于调试的日志类
ServerSocket socket=null;
Socket client=null;
SMTPSession session;//用于处理SMTP操作
int iPort=25; try
{
socket=new ServerSocket(iPort);
}
catch(IOException e)
{
log.error("Could not listen on port " + Integer.toString(iPort));
System.exit( -1);
} log.info("SMTP server is ready on port " +
Integer.toString(iPort)); while(true)
{
try
{
client=socket.accept();
session=new SMTPSession(client);
session.start();
}
catch(IOException e)
{
log.error("SMTP server: accept failed on port " +
Integer.toString(iPort));
}
}
}}
/**
*the banker class .
*/class Banker {
final int m = 3;
final int n = 3;
final int number = 50;
int[] avail = new int[n];
int[][] max = new int[m][n];
int[][] need = new int[m][n];
int[][] alloc = new int[m][n];
boolean[] finished = new boolean[m]; //start methord
public void start() {
init();
while (true) {
request();
}
}
/**对程序初始化。*/
void init() {
for (int i = 0; i < n; i++) {
avail[i] = (int)(number * Math.random());
}
System.out.println("系统资源:"); Operate.print(avail); for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
max[i][j] = (int)(avail[j] * (Math.random()));
need[i][j] = max[i][j];
alloc[i][j] = 0;
}
} System.out.println("最大需求:");
Operate.print(max);
System.out.println("已满足的需求:");
Operate.print(alloc);
System.out.println("尚未满足的需求:");
Operate.print(need);
}
/**产生并提交请求*/
void request() {
int p = (int)(m * Math.random());
//the thread has finshed
if (finished[p]) {
return;
} int[] req = new int[n]; //the resources that p resquested if (Math.random() > 0.5) {
//以系统资源为界,可能被第一级检查否决,容易引发不安全态
for (int i = 0; i < n; i++) {
req[i] = (int)Math.round((avail[i] * Math.random()));
}
} else {
//以未满足的需求为界,不会被第一级检查否决,不容易引发不安全态
for (int i = 0; i < n; i++) {
req[i] = (int)Math.round((need[p][i] * Math.random()));
}
} System.out.println("进程 " + p + " 发出请求:");
Operate.print(req);
submit(p, req);
}
/**接受一个申请,并予以解决
* @param p 线程号
* @param req 请求的资源向量*/
void submit(int p,int[] req) { if (test(p,req)) //the banker tests the requrst to see whether it's safe.
{
//p号线程的请求得到许可,进行分配。
Operate.subtract(avail,req);
Operate.add(alloc[p],req);
Operate.subtract(need[p],req);
System.out.println("许可请求."); if (Operate.equals(alloc[p],max[p])) {
System.out.println("进程 " + p + " 运行结束.");
finished[p] = true;
Operate.sleep(3000);
Operate.add(avail,max[p]);
}
} else {
System.out.println("否决请求.");
}
System.out.println("系统资源:");
Operate.print(avail);
System.out.println("已满足的需求:");
Operate.print(alloc);
System.out.println("尚未满足的需求:");
Operate.print(need);
if (getUnfinished() == 0) {
System.out.println("所有进程均已结束。");
System.exit(0);
}
} /**用银行家算法检查。
* @return 若允许分配,返回true;否则返回false。*/
boolean test(int p,int[] req) {
//第一级检查:是否超过未满足的需求量或系统资源量
for(int i = 0; i < n; i++) {
if (req[i] > need[p][i] || req[i] > avail[i]) {
System.out.println("对 " + i + " 资源不合法的请求数 " + req[i]);
return false;
}
}
Operate.sleep(); //第二级检查:是否引发系统的不安全态 int[][] needCopy = new int[m][n];
int[][] allocCopy = new int[m][n];
int[] availCopy = new int[n];
boolean[] finishedCopy = new boolean[m];
Operate.copy(needCopy,need);
Operate.copy(allocCopy,alloc);
Operate.copy(availCopy,avail);
Operate.copy(finishedCopy,finished);
//假设资源已分配给了线程p
Operate.subtract(needCopy[p],req);
Operate.subtract(availCopy,req);
Operate.add(allocCopy[p],req);
//算出未完成的线程有几个
int unfinished = getUnfinished();
int safe[] =new int[unfinished]; /*内循环每完成一次须有一个线程结束,否则处于不安全态
外循环完成时应能结束所有线程*/
for (int i = 0; i < unfinished; i++)
{
boolean possible = false; for (int j = 0; j < m; j++)
{
//Operate.afford意为前者能供应后者的需求
if (!finishedCopy[j] && Operate.afford(availCopy, needCopy[j]))
{
//把后者加到前者身上
Operate.add(availCopy,allocCopy[j]);
finishedCopy[j] = true;
possible = true;
safe[i]=j; break;
}
}//inner for loop if (!possible)
{
System.out.println("若分配系统将处于不安全态.");
return false;
}
} //outer for loop System.out.print("the safe sequences is ");
Operate.print(safe); //print the safe sequences return true;
} int getUnfinished() {
int unfinished = 0;
for (int i = 0; i < m; i++) {
if (!finished[i]) {
unfinished++;
}
}
return unfinished;
} /**调试用的*/
/*
void debug() {
int[][] debugNeed = {
{15, 3, 6},
{27, 13, 4},
{0, 0, 0 }
};
int[][] debugAlloc = {
{9, 14, 32},
{3, 13, 0},
{32, 16, 29 }
};
int[] debugAvail = {34,36,30};
boolean[] debugFinished = {false,false,true};
Operate.copy(need,debugNeed);
Operate.copy(avail,debugAvail);
Operate.copy(alloc,debugAlloc);
Operate.copy(finished,debugFinished);
int[] req = {7,0,3};
int p = 0;
System.out.println(test(p,req));
}
*/}
import java.util.Map;
class Account
{
String name;
//float amount;
//使用一个Map模拟持久存储
static Map storage = new HashMap();
static
{
storage.put("John", new Float(1000.0f));
storage.put("Mike", new Float(800.0f));
} public Account(String name)
{
//System.out.println("new account:" + name); this.name = name;
//this.amount = ((Float)storage.get(name)).floatValue();
} public synchronized void deposit(float amt)
{
float amount = ((Float)storage.get(name)).floatValue();
storage.put(name, new Float(amount + amt));
} public synchronized void withdraw(float amt)
throws InsufficientBalanceException
{
float amount = ((Float)storage.get(name)).floatValue();
if (amount >= amt) amount -= amt;
else throw new InsufficientBalanceException();
storage.put(name, new Float(amount));
} public float getBalance()
{
float amount = ((Float)storage.get(name)).floatValue();
return amount;
}
} 在新的Account类中,我们采用一个HashMap来存储账户信息。Account由ATM类通过login登录后使用:public class ATM
{
Account acc;
//作为演示,省略了密码验证
public boolean login(String name)
{
if (acc != null) throw new IllegalArgumentException("Already logged in!");
acc = new Account(name);
return true;
} public void deposit(float amt)
{
acc.deposit(amt);
} public void withdraw(float amt) throws InsufficientBalanceException
{
acc.withdraw(amt);
} public float getBalance()
{
return acc.getBalance();
} public void logout ()
{
acc = null;
}
}
线程同步!~
用Thread类的子类创建线程
public class Example19_1
{ static Lefthand left;static Righthand right;
public static void main(String args[])
{left=new Lefthand() ;//创建两个线程。
right=new Righthand();
left.start(); //线程开始运行后,Lefthand类中的run方法将被执行。
right.start();
}
}
class Lefthand extends Thread
{
public void run()
{
for(int i=0;i<=5;i++)
{ System.out.println("i am student");
try{sleep(500);}
catch(InterruptedException e){}
}
}
}
class Righthand extends Thread
{
public void run()
{
for(int i=0;i<=5;i++)
{System.out.println("i am oookkk");
try{sleep(300);}
catch(InterruptedException e){}
}
}
}
import java.applet.*;import java.awt.*;
public class Example19_2 extends java.applet.Applet implements Runnable
{ Thread circleThread;
public void start()
{
if (circleThread ==null)
{
circleThread =new Thread(this);
circleThread .start();
}
}
public void run ()
{
while(circleThread !=null)
{
repaint();
try{
circleThread .sleep(1000);
}
catch(InterruptedException e){}
}
}
public void paint(Graphics g)
{double i=Math.random();
if(i<0.5)
g.setColor(Color.red);
else
g.setColor(Color.blue);
g.fillOval(100,100,(int)(100*i),(int)(100*i));
}
public void stop()
{
circleThread.yield();
circleThread =null;
}
}
import java.awt.*;
import java.awt.event.*;
public class Example19_3
{public static void main(String args[])
{Mywin win=new Mywin();win.pack();
}
}
class Mywin extends Frame implements Runnable
{ Button b=new Button("ok");int x=5;
Thread bird=null;
Mywin()
{setBounds(100,100,120,120);setLayout(new FlowLayout());
setVisible(true);
add(b);b.setBackground(Color.green);
addWindowListener(new WindowAdapter()
{public void windowClosing(WindowEvent e)
{System.exit(0);}} );
bird=new Thread(this);//创建一个新的线程,窗口做目标对象,
//替线程bird实现接口Runnable。
bird.start(); //在创建窗口时又开始了线程bird。
}
public void run() //实现bird的操作。
{while(true)
{ x=x+1;
if(x>100) x=5;
b.setBounds(40,40,x,x);
try{bird.sleep(200);}
catch(InterruptedException e){}
}
}
}
[email protected]
很经典的网站!
我接分了!谢!