问题描述
不是说notifyAll()是让所有挂起线程恢复的吗?下面代码怎么只恢复了其中t51的线程。。。class A5 implements Runnable{ int i=0; String name; public void run() { while(true) { i++; System.out.println(name+"Z="+i); if(i==5){ try{ 挂起线程A5();} catch(Exception e){} } try{ Thread.sleep(1000);} catch(Exception e){} } } public synchronized void 挂起线程A5() throws InterruptedException { wait(); } public synchronized void 恢复线程A5() { notifyAll(); }}public class Example15{ public static void main(String args[]) { int m=0; A5 t51=new A5(); //线程A5的目标对象 t51.name="张一"; Thread thread=new Thread(t51); thread.setName(t51.name); A5 t52=new A5(); //线程A5的目标对象 t52.name="张二"; Thread thre=new Thread(t52); thre.setName(t52.name); thre.start(); thread.start(); while(true) { m++; System.out.println("我是主线程m="+m); if(m==10) { System.out.println("让全部线程继续工作"); try { t51.恢复线程A5(); } catch(Exception e){} break; } try{ Thread.sleep(1000); } catch(Exception e){} } }}
解决方案
public class Example15 {public static void main(String args[]) {int m=0; Object oo = new Object();A5 t51=new A5(); //线程A5的目标对象 t51.name="张一"; t51.synchronizedObject = oo;Thread thread=new Thread(t51); //thread.setName(t51.name);A5 t52=new A5(); //线程A5的目标对象 t52.name="张二"; t52.synchronizedObject = oo;Thread thre=new Thread(t52); //thre.setName(t52.name);thre.start();thread.start(); while(true) {m++;System.out.println("我是主线程m="+m); if(m==10) {System.out.println("让全部线程继续工作"); try {t51.恢复线程A5();} catch(Exception e){} break;}try {Thread.sleep(1000);} catch(Exception e){} }} } class A5 implements Runnable {Object synchronizedObject;int i=0;String name; public void run() {while(true) {i++;if(i==5) {System.out.println(name+" 挂起."); try{挂起线程A5();} catch(Exception e){} } else {System.out.println(name+"Z="+i); }try{Thread.sleep(1000);} catch(Exception e){}if(i==15) {System.out.println(name+" 完成."); break;}}}public void 挂起线程A5() throws InterruptedException { synchronizedObject.wait();}public void 恢复线程A5() {synchronizedObject.notifyAll(); }} 1,多线程中常见的问题:wait、notify、notifyAll必须针对同一个同步对象,不显式指定同步对象,同步对象为This,t51的this和t52的this当然不同。2,我直接传入的一个相同的同步对象给两个线程,就好了。
解决方案二:
结果:引用张二Z=1我是主线程m=1张一Z=1张一Z=2我是主线程m=2张二Z=2张二Z=3我是主线程m=3张一Z=3张二Z=4张一Z=4我是主线程m=4张一 挂起.我是主线程m=5张二 挂起.我是主线程m=6张二Z=6张一Z=6张二Z=7张一Z=7我是主线程m=7张二Z=8我是主线程m=8张一Z=8张二Z=9张一Z=9我是主线程m=9我是主线程m=10让全部线程继续工作张一Z=10张二Z=10张一Z=11张二Z=11张一Z=12张二Z=12张一Z=13张二Z=13张一Z=14张二Z=14张一Z=15张二Z=15张一 完成.张二 完成.