• Post Reply Bookmark Topic Watch Topic
  • New Topic

Thread throwing an exception  RSS feed

 
Haroon Iqbal
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
Sorry if this is in the wrong place, just move it if it is.

I have a problem trying to get a thread to throw an exception. The problem is that the run method cannot throw an exception. If I describe my problem maybe someone can come up with a better approach.

I am creating two threads ThreadA and ThreadB. ThreadA has to peform some code within a timelimit otherwise it should go to some error routine.

public class ThreadA extends Thread
{
try
{
// create a new thread with the time limit
ThreadB timer = new ThreadB(100000);
timer.start();

// do some other stuff within time limit
}
catch (Exception e)
{
e.printStackTrace();
// do out of time routine
}
}

The best I can do is to get ThreadB to print out "Time out" if the timelimit is reached and ThreadA is still executing. Is there anyway for threadB to throw an exception back to threadA? Is there a better way to do this?

Thanks
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, welcome to the ranch!

There's no way to throw from run() and catch back in the original thread as you showed. This makes sense because the original thread may have gone on to do other things by the time the runnable throws an exception.

There is a rather twisted solution. See THIS CHAPTER on Callable and FutureTask to solve this very problem. I'm not sure you'll like the finished product, though.

There are many kinds of inter-thread communication like wait-notify, join, semaphores, locks, publish-subscribe etc. Dig through the concurrent package in JDK5 and see if any of these look interesting.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!