线程类的interrupt()方法可对某一线程进行中断,例子如下:
public class SleepBlocked implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
try {
TimeUnit.SECONDS.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("Interupted Exception");
}
System.out.println("Exiting SleepBlocked.run()");
}
}
=======================
public class Interrupting {
private static ExecutorService exec=Executors.newCachedThreadPool();
static void test(Runnable r) throws InterruptedException{
Future<?> f=exec.submit(r);
TimeUnit.MILLISECONDS.sleep(100);
System.out.println("Interrupting "+r.getClass().getName());
f.cancel(true); //中断运行的线程
//cancel()方法是一种中断由Executor启动的单个线程的方式
System.out.println("Interrupt set to "+r.getClass().getName());
}
public static void main(String[] args) throws InterruptedException{
test(new SleepBlocked());
//这里SleepBlocked是可中断的
TimeUnit.SECONDS.sleep(3);
System.out.println("Aborting with System.exit(0)");
System.exit(0);
}
}
-------------运行结果如下:
Interrupting com.test.thread.block.SleepBlocked
Interrupt set to com.test.thread.block.SleepBlocked
Interupted Exception
Exiting SleepBlocked.run()
======================
有些资源是无法中断的比如IO等,实例如下:
public class IOBlocked implements Runnable{
private InputStream is;
public IOBlocked(InputStream is) {
this.is=is;
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Waiting For Read...");
try {
is.read();
} catch (IOException e) {
// TODO Auto-generated catch block
if(Thread.currentThread().isInterrupted()){
System.out.println("Interrupted from blocked I/O");
}else{
throw new RuntimeException(e);
}
}
System.out.println("Exiting IOBlocked.run()");
}
}
=======================
上面的测试方法修改为test(new IOBlocked(System.in)),这时候的运行结果为:
Waiting For Read...
Interrupting com.test.thread.block.IOBlocked
Interrupt set to com.test.thread.block.IOBlocked
Aborting with System.exit(0)
=============================
另外synchronized也是无法中断的,示例如下:
public class SynchronizedBlocked implements Runnable{
public synchronized void f(){
while(true)
Thread.yield();
}
public SynchronizedBlocked() {
// TODO Auto-generated constructor stub
new Thread(){
@Override
public void run() {
// TODO Auto-generated method stub
f();
}
}.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Try to call f");
f();
System.out.println("Exting SynchronizedBlocked.run()");
}
}
========================
将测试方法修改为test(new SynchronizedBlocked()),执行结果如下:
Try to call f
Interrupting com.test.thread.block.SynchronizedBlocked
Interrupt set to com.test.thread.block.SynchronizedBlocked
Aborting with System.exit(0)
因为这里的f()方法一直不释放锁,interrupt()方法也无法使它停止