Java notify() run before wait()?

后端 未结 3 1875
渐次进展
渐次进展 2021-01-05 11:57
public class ThreadA {
    public static void main(String[] args){
        ThreadB b = new ThreadB();
        b.start();

        synchronized(b){
            try{
          


        
3条回答
  •  难免孤独
    2021-01-05 12:19

    One of the many possible solutions for your problem is:

    public class ThreadA {
      public static final CyclicBarrier barrier = new CyclicBarrier(2);
    
      public static void main(String[] args) {
        ThreadB b = new ThreadB();
        b.start();
        try {
          barrier.await();
          System.out.println("Total is: " + b.total);
        } catch (InterruptedException | BrokenBarrierException ex) {
        }
      }
    }
    
    class ThreadB extends Thread {
        int total;
    
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                total += i;
            }
            try {
              ThreadA.barrier.await();
            } catch (InterruptedException | BrokenBarrierException ex) {
            }
        }
    }
    

提交回复
热议问题