0

Is there any difference of placing timlesProc(100); inside or outside synchronized block like shown commented line in ThreadA.

According to my understanding there is no difference, because both threads are in running mode and both can be executed in the same time. But according experiments, when timlesProc(100); is inside synchronized - it always runs first, then b.sync.wait(); and no 'wait forever' problem. When timlesProc(100); outside synchronized - I always get 'waiting forever'. Why it is so, or my understanding is not correct?

class ThreadA {
public static void timlesProc(int count)
{
         for(int i=0;i<count;i++) 
           {
              System.out.println(Thread.currentThread().getName()+" "+ Integer.toString(i));
           }
}

    public static void main(String [] args) {
         ThreadB b = new ThreadB();

         b.start();

         //timlesProc(100);
         synchronized(b.sync) 
         {
            timlesProc(100);


            try 
            {
               System.out.println("Waiting for b to complete...");
               b.sync.wait();
               System.out.println("waiting done");

            } catch (InterruptedException e) {}



         }




     }
  }




class ThreadB extends Thread {   

     Integer sync = new Integer(1);
     public void run() {


        synchronized(sync) 
        {
           sync.notify();
            System.out.println("notify done");

        }  


     }
  }
4

2 回答 2

4

你有一个竞争条件。如果该timlesProc方法在 之外synchronized,则很有可能您将进行上下文切换,而另一个Thread将能够执行获取锁并通知main线程(即使它没有等待)。然后当你到达

b.sync.wait();

你永远等待,因为没有任何东西可以留下notify()

如果你把timlesProc里面的synchronized,你到达wait()然后得到通知。然后程序结束。

有关您的程序永远等待的另一种可能性,请参阅Cruncher 的答案。

于 2013-09-26T14:41:08.453 回答
2

实际上,即使timlesProc调用在同步块内,仍然存在竞争条件,只是不太可能发生。

如果b.start()发生这种情况,并且它在主线程之前获取同步锁,那么它仍然会首先通知导致 Sotirios Delimanolis 在他的回答中提到的相同问题。

于 2013-09-26T14:49:23.707 回答