Notify not getting the thread out of wait state

前端 未结 3 1291
盖世英雄少女心
盖世英雄少女心 2021-01-28 05:28

I am trying to use 2 threads. 1 thread prints only odd number and the other thread prints only even number and It has to be an alternative operation.

Eg:



        
3条回答
  •  太阳男子
    2021-01-28 06:15

    Problem is that in one case you are taking lock on Thread t [synchronized (t) ] while in other case you are taking lock on TheadA object itself [synchronized(this)].

    If you want threads to talk to each other then both should take lock on same object only then wait notify will work as you expect.

    Edit:

    There is another problem in your program, you are not using any variable to coordinate between 2 threads. SO you may see output like this 2,1,4,3...so on. Point is threads will work alternately but not in sequence. So you should share a single variable between 2 threads which should be incremented. Second issue is you are not taking care of spurious wake up calls [read some docs on this], you should always have wait called inside a while loop.

提交回复
热议问题