File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to make code execute in its own Thread

 
Barry Brashear
Ranch Hand
Posts: 303
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:

 
Barry Brashear
Ranch Hand
Posts: 303
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3061
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Barry Brashear
Ranch Hand
Posts: 303
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic