火树银花-月色 2017-10-23 05:41 采纳率: 0%
浏览 2082

java多线程中死循环问题

public class Test{
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(); //恢复thread线程
}
}
class MyThread extends Thread{
int number=0;
boolean stop=false;
boolean getStop(){
return stop;
}
public synchronized 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();
}
}
为啥主函数里面死循环无法获取已经更改的thread.getStop()

展开全部

  • 写回答

4条回答 默认 最新

  • 鼠晓 博客专家认证 2017-10-23 18:46
    关注

    可能是緩存,,,
    改成下面的试试

     volatile boolean stop = false;
    
    评论
编辑
预览

报告相同问题?