In Java 5, Thread.interrupt() is not encouraged. Instead, you are encouraged to use
<1st way> aExecutorService.shutdownnow();
<2nd way> aFuture<?>.cancel(true);
For the 1st way, a interrupt message is sent to all Runnables.
For the 2nd way, true means, a interrupt message can be sent to the related Runnables.
There are 2 ways to submit a Runnable to a executorService instance.
<1st way> use execute(aRunnable).
Generally, Runnable object should be sent in this way.
<2nd way> use submit(aRunnable). submit(aCallable<?>)
Generally, all Callable<?> should be sent in this way, since this is the only way that you can get a Future<?> response where you can get the result.
aRunnable can also be sent in this way, the only reason to get a uselss Future<?> is because you want to call cancel<boolean> on the Future<?> object. If you call cancel(true) on it, acutally you are sending a interrupt message to the Runnable.
package test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class Thread5Interrupt
{
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException
{
ExecutorService service = Executors.newCachedThreadPool();
Future<?>[] handleList = new Future<?>[10];
for(int i = 0; i < 10; i++)
{
handleList[i] = service.submit(new RunIt());
}
TimeUnit.SECONDS.sleep(1);//wait for all runnable starting up..
// service.shutdownNow(); //Send interrupt call to all Runnables.
for(Future<?> temp : handleList) //Send interrupt call to Runables one by one
{
boolean mayInterruptIfRunning = false;
temp.cancel(mayInterruptIfRunning);
}
service.shutdown();
}
}
class RunIt implements Runnable
{
public void run()
{
System.out.println(Thread.currentThread().getName() + " start!");
try
{
TimeUnit.SECONDS.sleep(10);
}
catch (InterruptedException e)
{
System.out.println(Thread.currentThread().getName() + " interrupted! Interrupted value: " + Thread.currentThread().isInterrupted());
}
System.out.println(Thread.currentThread().getName() + " finished!");
}
}