• Post Reply Bookmark Topic Watch Topic
  • New Topic

How do I use two threads synchronized

 
bob morkos
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have a delete method that has to be executed first , before I call the method that inserts. The delete method (deletes in batches of 2000)and waits. The problem was that when I run the program, my delete method was not executed fully and when I called the batch inserts method I had a problem, because the delete did not finish. How can I code this, I tried something like below and it does not work, frozen? Can anyone help?

public synchronized delete(){
// code
// procedure that deletes in batch of 2000
wait();
notify();
}

public syncronized insert(ArrayList ll){

}
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If your main thread is going to block until the delete thread is done, I'm thinking it might as well all be in one synchronous thread anyhow. But I"m sure that's not what you want.

If you really want the main thread to keep running and do interesting things while the deletes are running you need to coordinate things, which I guess was your question. A couple ideas come to mind:

In the main thread the driver class spawns the delete thread and goes on its way. On completion, the delete thread publishes an event back to the driver class. The driver class spawns yet another thread to do the inserts. Note that the event handling probably happens on the delete thread, but in the driver class. An interesting mix.

Completely different: Write a class that blocks waiting to find a command in a queue. When it finds a command it executes the command. Spawn this class on its own thread and then put two commands in the queue: a delete command and an insert command. They'll be executed in sequence on the other thread. The Jakarta Commons Thread Pool has a very simple implementation of this technique. You'd essentially be using it as a thread pool of one thread.

BTW: "command" refers to the Gang of Four command pattern. A command object is an instance of a class that knows how to do some work, like delete or insert stuff. All your commands implement an interface with a method like execute() so the worker thread can execute any command it finds in queue.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!