Reputation: 119
Sorry for my English.
I have a Thread with method:
@Override
public void run()
{
try
{
System.out.println( "Hello world" );
Thread.sleep( 10 );
}
catch( InterruptedException e )
{
e.printStackTrace();
}
finally
{
while( true )
System.out.println( "FINALLYYY" );
}
}
and I suggest, that this thread never can be stopped! After calling methods interrupt or stop - in finally block thread will start infinity loop.
How I can force the thread to stop?
Upvotes: 0
Views: 1074
Reputation: 119
So... I Found next solution:
worker.interrupt();
while( worker.isAlive() )
worker.stop();
It's not ideal solution, but in my case, it's best... Every call worker.stop - throw unchecked exception "ThreadDeath" and each finally block will be "skiped". It should stop the thread.
Upvotes: 1
Reputation: 1393
You may try to control how the user's thread is executed (at least while you control user's threads execution). For instance, you can use Future from concurrency package (don't forget to handle exceptions):
ExecutorService executor = Executors.newSingleThreadExecutor();
Future task = executor.submit(usersThread);
try {
task.get(1, TimeUnit.MINUTES);
} finally {
task.cancel(true);
}
If you can't control the code inside the Thread, then you may control the code, which is used from it. For instance, consider the following approaches:
Upvotes: 0
Reputation: 1723
In your current set up, you could stop the thread by calling the interrupt()
method on the Thread
that is executing.
Either way, to allow the Thread to terminate gracefully, you will have to expose a way to terminate that thread, either by exposing the thread so it can be interrupted, or by providing a 'kill switch' in the way suggested by David ten Hove.
Upvotes: 0
Reputation: 2826
The Thread stop and interrupt methods are not the best way to solve this problem. Add a boolean variable to your thread and check it in your while statement.
For example:
private volatile boolean keepGoing = true;
public void stopTheThread() {
keepGoing = false;
}
@Override
public void run()
{
try
{
System.out.println( "Hello world" );
Thread.sleep( 10 );
}
catch( InterruptedException e )
{
e.printStackTrace();
}
finally
{
while( keepGoing )
System.out.println( "FINALLYYY" );
}
}
Upvotes: 1