該例子中未使用線程鎖,只是給學習線程中其他線程的例子。
線程通過調用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){
}
}
}
}
}