0

我开发了下面的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,请告知。

4

1 回答 1

0

您可以将引用b2等待传递给运行您要执行通知的线程的类。

你必须synchronized在你等待()的对象上。

于 2012-04-19T18:15:26.087 回答