Java_螞蟻吃蛋糕(在線程中啓動其他線程)

該例子中未使用線程鎖,只是給學習線程中其他線程的例子。

線程通過調用start()方法將啓動該線程,使之從新建狀態進入就緒隊列排隊。一旦輪到它來享用CPU資源時,就可以脫離創建它的主線程獨立開始自己的生命週期中。
在這裏插入圖片描述

public class thread_start_anotherThread {
    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("黑螞蟻");
        house.setAttachThread(antTwo);
        antOne.start();//紅螞蟻先吃
    }
}

class House implements Runnable{

    int cake = 10;
    Thread attachThread;

    public void setCake(int c){
        cake = c;
    }

    public void setAttachThread(Thread t){
        attachThread = t;
    }

    @Override
    public void run() {
        int m=2;
        while(true){
            if(cake<=0){
                System.out.println(Thread.currentThread().getName()+"進入死亡狀態");
                return;
            }
            System.out.println(Thread.currentThread().getName()+"吃"+m+"克蛋糕。");
            cake = cake-m;
            System.out.println(Thread.currentThread().getName()+"發現蛋糕還剩"+cake+"克");
            if(cake<=4){
                try{
                    attachThread.start();//啓動黑螞蟻
                }catch (Exception e){

                }
                try{
                    Thread.sleep(1000);
                }catch (Exception e){

                }
            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章