synchronized線程鎖
把🐜要做的操作封裝在一個synchronized方法中,即保證一直🐜沒有吃完m克蛋糕時,另一隻🐜不可以吃蛋糕。
public class ants_eat_cakes {
public static void main(String args[]){
House house = new House();
house.setCake(10);
Thread antOne,antTwo;
antOne = new Thread(house);
antOne.setName("紅螞蟻");
antTwo = new Thread(house);
antTwo.setName("黑螞蟻");
antOne.start();
antTwo.start();
}
}
class House implements Runnable{
int cake = 10;
public void setCake(int c){
cake = c;
}
private synchronized void antDoing(){
int m = 2;
System.out.println(Thread.currentThread().getName()+"想吃"+m+"克蛋糕");
cake = cake - m;
if(cake>=0){
System.out.println(Thread.currentThread().getName()+"發現蛋糕還剩"+cake+"克");
}
else {
System.out.println(Thread.currentThread().getName()+"發現蛋糕沒了");
}
}
@Override
public void run() {
while(true){
antDoing();
if(cake<=0){
System.out.println(Thread.currentThread().getName()+"進入死亡狀態");
return;
}
try{
Thread.sleep(1000);
}catch (Exception e){
}
}
}
}