创建一个和尚类
public class Basket {
private int count = 100 ;
//和尚数量 ==没吃馒头的和尚数量
private int numMonks = 30 ;
public synchronized int getBread(Monk monk){
//和尚第一次吃
if(monk.count == 0){
int temp = count ;
count -- ;
numMonks -- ;
return temp ;
}
//和尚还可以吃的情况
else if(monk.count < Monk.MAX){
//判断是否有多余的馒头
if(count > numMonks){
int temp = count ;
count -- ;
return temp ;
} else{
return -1 ;
}
}
return -1 ;
}
}
创建一个馒头类继承Thread类创建多线程
public class Monk extends Thread{
private String monkName ;
private Basket basket ;
//最少一个馒头
public static int MIN = 1 ;
//最多4个馒头
public static int MAX = 4 ;
//吃的馒头数
public int count ;
public Monk(Basket basket , String monkName){
this.basket = basket ;
this.monkName = monkName ; }
public void run() {
while(true){
int no = basket.getBread(this);
if(no ==-1){
break ;
}
else{
count ++ ;
System.out.println(monkName + "吃了编号为[" + no + "]的馒头");
}
}
System.out.println(monkName + "共吃了【" + count + "】馒头");
}
}
创建一个测试类
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Basket p=new Basket();
for(int i=0;i<30;i++){
new Monk(p,"和尚" + (i+1)+":\t").start();
}
}
}