所謂的中斷操作:它並不會真正地中斷一個正在運行的線程,而只是發出中斷請求,然後由線程在下一個合適的時刻中斷自己。
調用一次interrupt中斷請求,再次調用就是把中斷狀態恢復
處理中斷異常:
1》傳遞異常
2》恢復中斷狀態
這裡有一個示例,用來限時運行任務,在規定的時間內,不論程序是否響應中斷終止程序,還是沒有響應到中斷,我們都可以獲取到通過調用這個方法獲取結果,
也就是可以再規定的時間內獲取到處理結果,對結果如何處理,那就可以自己定義
package cn.study.concurrency;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
*
* @author xiaof
*
*/
public class TimeCount {
private static final ScheduledExecutorService cancelExec = Executors.newSingleThreadScheduledExecutor();
/**
*
* @param r 線程
* @param timeout 任務超時限定
* @param unit 時間單元
* @throws Throwable
*/
public static void timedRun(final Runnable r, long timeout, TimeUnit unit) throws Throwable
{
class RethrowableTask implements Runnable
{
//拋出的異常
private volatile Throwable t;
@Override
public void run() {
try {
r.run();
} catch (Throwable e) {
this.t = e;
}
}
/**
* 當運行超時,或者程序運行正常退出的時候,後面進行控制的時候調用這個返回給調用者
* @throws Throwable
*/
void rethrow() throws Throwable
{
//這個t可以自己包裝,或者返回其他數據,這個可以根據不同的業務來定
//這裡甚至可以保持當前狀態到本地,在下次運行的時候,先讀取本地數據,恢復到當前狀態,留到以後操作
if(t != null)
throw t;
}
}
RethrowableTask task = new RethrowableTask();
final Thread taskThread = new Thread(task);
taskThread.start(); //啟動外部線程
cancelExec.schedule(new Runnable()
{
public void run()
{
//啟動中斷異常
taskThread.interrupt();
}
}, timeout, unit);
//等待線程的終止,用來應對即使任務不響應中斷,限定時間一到,最後仍可以拋出異常到這個方法的調用者
taskThread.join(unit.toMillis(timeout));
//拋出異常
task.rethrow();
}
}