wood burning stoves 2.0*
The moose likes Threads and Synchronization and the fly likes How to make code execute in its own Thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "How to make code execute in its own Thread" Watch "How to make code execute in its own Thread" New topic
Author

How to make code execute in its own Thread

Barry Brashear
Ranch Hand

Joined: Jun 05, 2001
Posts: 303
I'd like to have code that's concerned with printing run in its own thread,\
however I don't want or need a run method. Is there a way to do that?

Thanks.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Not sure why you say "I don't want or need a run method," but you'll have to get over that if you want to run something in its own thread. You can just use an anonymous class if you want:



[Jess in Action][AskingGoodQuestions]
Barry Brashear
Ranch Hand

Joined: Jun 05, 2001
Posts: 303
Thanks. One more question. How can it be determined that the code in
the 2nd thresd call has completed in order to stop the thread?
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
The 2nd thread stops automatically when the run() method completes execution. You don't have to do any extra work to tell it to stop.


Java API Documentation
The Java Tutorial
Barry Brashear
Ranch Hand

Joined: Jun 05, 2001
Posts: 303
Thanks! One more teeny weeny question. Is it possible to throw any exceptions caught in the method called in the 2nd thread back to the caller.
I get compile errors when I try this. It says unhandled exception type for
the exception I'm catching.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

You can have a try/catch inside the run() method to handle the exceptions in that second thread, or you can use a callback of some kind. A callback is a method that the second thread can call to report its status. For example, something like



Now, one thing I didn't show is how the first thread knows that the second thread is done. The main way to do that is to use the "wait()" and notify()" methods, but that's another story...

I'm going to move this thread -- which I suspect will get longer -- to the "Threads and Synchronization" forum, and we'll continue it there.
 
Don't get me started about those stupid light bulbs.
 
subject: How to make code execute in its own Thread
 
Similar Threads
Synchronized Block
Thread, Runnable and their run() method
difference between start() and run()
Controlling listeners
target Runnable of a thread