publicclassExample{
publicstaticvoidmain(Stringargs[]){
Atarget=newA();//线程thread的目标对象
Threadthread=newThread(target);
thread.setName("张三");
thread.start();
while(target.getStop()==false){}
System.out.println("我是主线程,负责恢复"+thread.getName()+"线程");
target.restart();//恢复thread线程
}
}
classAimplementsRunnable{
intnumber=0;
booleanstop=false;
booleangetStop(){
returnstop;
}
publicvoidrun(){
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(Exceptione){}
}
try{Thread.sleep(1000);
}
catch(Exceptione){}
}
}
publicsynchronizedvoidhangUP()throwsInterruptedException{
wait();
}
publicsynchronizedvoidrestart(){
notifyAll();
}
}
求教,main方法中的空循环是做什么用的?初学线程,不是很理解。
while(target.getStop()==false){}
等待target线程结束,target线程运行在主线程main里面,如果没有这个空循环,主线程顺序执行,target还没有执行完得时候主线程已经执行完退出了,会导致target也退出。
publicstaticvoidmain(Stringargs[]){
Atarget=newA();//线程thread的目标对象
Threadthread=newThread(target);
thread.setName("张三");
thread.start();
while(target.getStop()==false){}
System.out.println("我是主线程,负责恢复"+thread.getName()+"线程");
target.restart();//恢复thread线程
}
}
classAimplementsRunnable{
intnumber=0;
booleanstop=false;
booleangetStop(){
returnstop;
}
publicvoidrun(){
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(Exceptione){}
}
try{Thread.sleep(1000);
}
catch(Exceptione){}
}
}
publicsynchronizedvoidhangUP()throwsInterruptedException{
wait();
}
publicsynchronizedvoidrestart(){
notifyAll();
}
}
求教,main方法中的空循环是做什么用的?初学线程,不是很理解。
while(target.getStop()==false){}
等待target线程结束,target线程运行在主线程main里面,如果没有这个空循环,主线程顺序执行,target还没有执行完得时候主线程已经执行完退出了,会导致target也退出。