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()
可能是緩存,,,
改成下面的试试
volatile boolean stop = false;
告诉你原因吧
每个线程在运行过程中都有自己的工作内存,那么线程主线程在运行的时候,会将stop变量的值拷贝一份放在自己的工作内存当中,那么当线程MyThread更改了stop变量的值之后,但是还没来得及写入主存当中,线程MyThread转去做其他事情了,当然你这是挂起了,那么主线程由于不知道线程MyThread对stop变量的更改,因此还会一直循环下去......
另外volatile是无法保证对变量的任何操作都是原子性的。
所以感觉是你的synchronized没有用到位置上
这样应该就对了
synchronized boolean getStop() {
return stop;
}
而你的public synchronized void run() {
上面的synchronized可以不用