File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes communucation of two threads Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "communucation of two threads" Watch "communucation of two threads" New topic

communucation of two threads

eswar kumar
Ranch Hand

Joined: Oct 20, 2002
Posts: 98
how do u communicate two threads?
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
What kind of communication do you see a need for? Some simple things are pretty normal in spite of threads being involved.
Say ObjectA is running in Thread1 and ObjectB is runing in Thread2. And say B is doing some kind of loop which is why we put it in a thread in the first place. And we'd like to tell it to stop. ObjectA can call a method on ObjectB that simply sets a variable, say keepRunning=false. That method call runs on Thread1. But the next time B goes through its loop on Thread2, it can look at the variable and see that it has been told to stop.
Another kind of thread communication happens in Swing. If you're doing a long-running task on its own thread so the Swing thread stays responsive to mouse clicks and such, and you want the task to update the GUI you should not directly update Swing widgets from the task thread. It confuses Swing and causes repaint problems. So there is a SwingUtil class that lets you put a command into a queue from the task thread. Some time soon the Swing thread sees the command on the queue - much like the variable above - and executes the command in the Swing thread. Pretty clever.
Do you have something trickier in mind? There's a whole branch of computer science in threading, semaphores, joining, etc.

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Vinod Chandana
Ranch Hand

Joined: Aug 26, 2003
Posts: 59
There is another way to communicate. You can always send an interrupt to a sleeping or waiting thread and catch the exception and do whatever you want to in the catch block. Hope this helps.
Originally posted by eswar kumar:
how do u communicate two threads?
I agree. Here's the link:
subject: communucation of two threads
It's not a secret anymore!