开发者

How to wait for the thread and handler to get initialised

I am writing an application. I came across scenario in such a way that, i have to create two threads, thread1 will be created first and thread2 will be created开发者_StackOverflow second. thread1 has to post in to the handler of the thread2. But as system is fast, before the time thread2 got created and handler got initialised , thread1 started posting the message objects to thread2. Due to which i am facing unexpected behaviour.

Please let me know how to wait in the thread1 for the thread2 to get started and handler is initialised. I tried polling mechanism, as it affects the system performance this fix is not getting accepted.


Just use something like that:

// @ Thread 1
synchronized( someMonitor ) {
  someMonitor.wait( /* time? */ );
}

// @ Thread 2
synchronized( someMonitor ) {
  someMonitor.notify();
}

So Thread 1 will wait until Thread 2 notifies. I would check before the wait if the condition is already set.


Another way is to create thread 2 from thread 1 so that the queue, or whatever, that thread 2 uses for input is created before thread 1 gets around to posting stuff.

Rgds, Martin


I recommend looking at the CountDownLatch class in JDK.

http://www.java2s.com/Code/Java/Threads/AnexampleofCountDownLatch.htm

http://download.oracle.com/javase/6/docs/api/java/util/concurrent/CountDownLatch.html


You need to rethink your design: It looks like you are working on a Producer/Consumer model, so you might want to use a (Blocking)Queue for the message exchange. Create it off both threads and pass it to both the Producer and Consumer on creation time. In that situation it doesn't matter which thread start to run first: if the producer then the queue starts to get filled, if the consumer, then it will wait until the producer has started as well.


Your first option is to make the message queue global.

The second is to create thread2 from thread1.

Third is to have a synchronization object (Object.wait,notify,interrupt).

Still, I think the same as Mark does, that the problem is in your design, and you cant make up a good solution for this problem if it's the inherent design is not appropriate.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜