views:

76

answers:

1

HI all,

I am having a thread Checker (extends thread class) which keeps on decreasing the numbers from 1000 to 0 and stops when number reaches 0. Also the sleep time between the subtractions is 10 seconds hence it goes on like 1000, 990, 980..... and so on. This count is stored permanently and hence will not get reset to 1000 after it is decreased.

I need to implement following situation:

  1. I have 2 classes A and B having main() method. They start this thread in main(). Now it should be like if class A is running the Checker thread then thread in class B should wait unless and until class A finishes its execution.
  2. Class B' thread should not start even if Checker thread in Class A is Sleeping.
  3. Class B's thread will start the execution only if Class A's Checker Thread is stopped.

How to implement such synchronization between class A and B?

Also starting the checker thread from class A and B is completely random. Any thread can be started any time. If Checker from A starts and B is running then it should wait till B completely finishes off or stopped. And vice versa.

+1  A: 

Let them share a single thread executor and submit the tasks to it instead.

Executor executor = Executors.newSingleThreadExecutor();

Here's an extract of relevance from the Executors#newSingleThreadExecutor() javadoc:

Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time.

BalusC