我开发了以下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,如何实现这一点,因为通知线程可以接收任何一个线程,但我只想要b2,请指教。
答案 0 :(得分:0)
您可以将引用b2
等待传递给运行您想要通知的线程的类。
您必须{I}上等待对象({1}}。