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 Two threads - one does the work Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Two threads - one does the work" Watch "Two threads - one does the work" New topic

Two threads - one does the work

Jason Hocker
Ranch Hand

Joined: Jul 23, 2003
Posts: 132
Here is what I want. I have an application that has a ServerSocket for incoming transactions. Usually this is one thread per incoming socket connection.
What I want is to add a second thread to do all the work. So the data comes in from the socket, and a second thread starts. When the second thread needs more data, it will wait for the first thread to send a response over the socket, get another request, and then have the second thread continue with this new data.
Im having trouble implementing this second thread. I'm confused how to have thread 1 wait while thread 2 works, and then have thread 2 wait while thread 1 gets the data.
I'm guessing that I'll need to store all instances of "thread 2" in a hashtable for the "thread 1"s to use in later transactions.
Yaroslav Chinskiy
Ranch Hand

Joined: Jan 09, 2001
Posts: 147
Can you give more explanation?
U can have one thread that has method sendRequest(request) and the thread will write all replies to a buffer. So now, the second thread reads the buffer and if it needs to send a request it will use thread1.sendRequest()

u can have the thread1 to be a singletone.
Jason Hocker
Ranch Hand

Joined: Jul 23, 2003
Posts: 132
Where I am getting confused is when to say notifyAll() and wait(), and what object to synchronize.
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
Jay, let me ask you. Dou you have to serve only one conenction at a time and don't want to start a new thread for each one? Or rather, you have to serve several connections simultaneously and you want only one thread for that.

SCJP2. Please Indent your code using UBB Code
I agree. Here's the link:
subject: Two threads - one does the work
It's not a secret anymore!