1个回答
展开全部
package know;
public class T31 {
public static int peaches=100;
public static synchronized int fetch(int num, int mypeach){
int i= peaches/2+peaches%2;
peaches-=i;
mypeach+=i;
System.out.println("第"+num+"只猴子抢到了桃子,这次抢到"+i+"个,现在有:"+mypeach+"个");
return mypeach;
}
public static void main(String[] args) throws InterruptedException {
Thread monkey1=new Thread(){
public void run(){
int mypeach=0;
while(peaches>1){
mypeach=fetch(1, mypeach);
}
}
};
Thread monkey2=new Thread(){
public void run(){
int mypeach=0;
while(peaches>1){
mypeach=fetch(2, mypeach);
}
}
};
Thread monkey3=new Thread(){
public void run(){
int mypeach=0;
while(peaches>1){
mypeach=fetch(3, mypeach);
}
}
};
monkey1.start();
monkey2.start();
monkey3.start();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询