挂起方法hangUP,如果不加synchronized,恢复后,后面的println为什么不能执行。
public class Example8_12{
public static void main(String args[]){
MyThread thread=new MyThread();
thread.setName("张三");
thread.start();
while(thread.getStop()==false){}
System.out.println("我是主线程,负责恢复"+thread.getName()+"线程");
thread.restart();
}
}
class MyThread extends Thread{
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();
}
}
不加synchronized:
public class Example8_12{
public static void main(String args[]){
MyThread thread=new MyThread();
thread.setName("张三");
thread.start();
while(thread.getStop()==false){}
System.out.println("我是主线程,负责恢复"+thread.getName()+"线程");
thread.restart();
}
}
class MyThread extends Thread{
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 void hangUP() throws InterruptedException{
wait();
}
public synchronized void restart(){
notifyAll();
}
}
首先你的stop变量必须这样声明volatile boolean stop = false;,不然你的例①都跑不出来
然后记得捕获异常的时候加上e.printStackTrace();方便查看日志
你这个错误在于wait必须把自己锁上,不然会抛出IllegalMonitorStateException异常,你没有打印错误,当然啥都看不出来了
你的疑问不就是hangUP没锁为什么没打印吗?因为不加锁会崩溃啊,你下面不有捕获异常吗,异常信息都不打印当然啥都看不到了
问答版主就是牛,从现在起只回论坛,不在踏入问答半步