• Post Reply Bookmark Topic Watch Topic
  • New Topic

Stopping and Starting Threads  RSS feed

 
Michael Scott
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have Java code that requires the 'sleep' method to be added in two places. Otherwise the code fails because of an unavailable resource. I'm interested in whether the code might be modified so that one thread stops before another starts. In other words, the process which is running when the code 'sleeps' does so on one thread, and the process which runs after the code 'sleeps' does so on another thread. This would seem to ensure that a resource is available when the second thread starts.

The two points in which sleep' is required are as follows.

1.) In this case, 'batCommand' is unavailable unless 'sleep' is added.

String batCommand = buffer.toString();
Runnable runnable = new BasicThread();
Thread thread = new Thread(runnable);
thread.sleep(8000);
Process batChild = Runtime.getRuntime().exec(batCommand);


2.) In this case, 'doc' is unavailable unless 'sleep' is added.

doc.save();
thread.sleep(8000);
RichTextItem body = doc.createRichTextItem("Test");


I'd appreciate any suggestions on how this code might be modified so that the threads stop and start as I've suggested.

Thanks.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm guessing in 1 you accidentally left out the line that says "thread.start()"?? If you start another thread and wait for it to finish, you're not getting any benefit. But you can do it easily:

Look up the doc on join() and see if that's what you need.

doc.save() may be a different problem. It looks like it starts another thread but doesn't give you access to it so you could join() it. If that's the case, see if doc has any kind of callback or event notification for when it's done.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at whether the following things give you any ideas:

- the Producer/Consumer pattern
- the Java 5 Future class
- Object.wait and Object.notifyAll
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!