public class Example{
public static void main(String args[]){
A target=new A(); //線程thread的目標(biāo)對(duì)象
Thread thread=new Thread(target);
thread.setName("張三");
thread.start();
while(target.getStop()==false){}
System.out.println("我是主線程,負(fù)責(zé)恢復(fù)"+thread.getName()+"線程");
target.restart(); //恢復(fù)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()+"恢復(fù)執(zhí)行");
}
catch(Exception e){}
}
try{ Thread.sleep(1000);
}
catch(Exception e){}
}
}
public synchronized void hangUP() throws InterruptedException{
wait();
}
public synchronized void restart(){
notifyAll();
}
}
求教,main方法中的空循環(huán)是做什么用的?初學(xué)線程,不是很理解。
while(target.getStop()==false){}
等待target線程結(jié)束,target線程運(yùn)行在主線程main里面,如果沒(méi)有這個(gè)空循環(huán),主線程順序執(zhí)行,target還沒(méi)有執(zhí)行完得時(shí)候主線程已經(jīng)執(zhí)行完退出了,會(huì)導(dǎo)致target也退出。
public static void main(String args[]){
A target=new A(); //線程thread的目標(biāo)對(duì)象
Thread thread=new Thread(target);
thread.setName("張三");
thread.start();
while(target.getStop()==false){}
System.out.println("我是主線程,負(fù)責(zé)恢復(fù)"+thread.getName()+"線程");
target.restart(); //恢復(fù)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()+"恢復(fù)執(zhí)行");
}
catch(Exception e){}
}
try{ Thread.sleep(1000);
}
catch(Exception e){}
}
}
public synchronized void hangUP() throws InterruptedException{
wait();
}
public synchronized void restart(){
notifyAll();
}
}
求教,main方法中的空循環(huán)是做什么用的?初學(xué)線程,不是很理解。
while(target.getStop()==false){}
等待target線程結(jié)束,target線程運(yùn)行在主線程main里面,如果沒(méi)有這個(gè)空循環(huán),主線程順序執(zhí)行,target還沒(méi)有執(zhí)行完得時(shí)候主線程已經(jīng)執(zhí)行完退出了,會(huì)導(dǎo)致target也退出。