[英]Regarding notifying a particular thread deleibrately
我开发了下面的java代码..
class ThreadB extends Thread {
public int totals;
public void run() {
synchronized(this) {
for(int i=0;i<100;i++) {
totals += i;
}
notify(); //want to notify only thread b2
}
}
}
另一类是...
class ThreadA {
public static void main(String [] args) {
ThreadB b1 = new ThreadB();
b.start();
ThreadB b2 = new ThreadB();
b2.start();
ThreadB b3 = new ThreadB();
b3.start();
ThreadB b4 = new ThreadB();
b4.start();
synchronized(b) {
try {
System.out.println("Waiting for b to complete...");
b1.wait();
b2.wait(); //only b2 to be notified
b3.wait();
b4.wait();
} catch (InterruptedException e) {}
System.out.println("Total is: " + b.totals);
}
}
}
不,请告诉我我只希望仅通知线程b2和b2,我将如何实现这一点,因为notify线程可以选择任何一个线程,但是我只希望b2请通知。
您可以将引用b2
等待传递给运行您要进行通知的线程的类。
您必须在您正在等待的对象上进行synchronized
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.