public class Example{
public static void main(String args[]){
A target=new A(); //線程thread的目標對象
Thread thread=new Thread(target);
thread.setName("張三");
thread.start();
while(target.getStop()==false){}
System.out.println("我是主線程,負責恢復"+thread.getName()+"線程");
target.restart(); //恢復thread線程
}
}
class A implements Runnable{
int number=0;
boolean stop=false;
boolean getStop(){
return stop;
}
public void run(){
while(true){
number++;
System.out.println(Thread.currentThread().getName()+"的number="+number);
if(number==3){
try{ System.out.println(Thread.currentThread().getName()+"被掛起");
stop=true;
hangUP();//掛起線程
System.out.println(Thread.currentThread().getName()+"恢復執行");
}
catch(Exception e){}
}
try{ Thread.sleep(1000);
}
catch(Exception e){}
}
}
public synchronized void hangUP() throws InterruptedException{
wait();
}
public synchronized void restart(){
notifyAll();
}
}
求教,main方法中的空循環是做什么用的?初學線程,不是很理解。
while(target.getStop()==false){}
等待target線程結束,target線程運行在主線程main里面,如果沒有這個空循環,主線程順序執行,target還沒有執行完得時候主線程已經執行完退出了,會導致target也退出。