1. 程式人生 > 實用技巧 >執行緒相關工具類

執行緒相關工具類

public class Threads {

/**
* sleep等待,單位為毫秒,忽略InterruptedException.
*/
public static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
// Ignore.
return;
}
}

/**
* sleep等待,忽略InterruptedException.
*/
public static void sleep(long duration, TimeUnit unit) {
try {
Thread.sleep(unit.toMillis(duration));
} catch (InterruptedException e) {
// Ignore.
return;
}
}

/**
* 按照ExecutorService JavaDoc示例程式碼編寫的Graceful Shutdown方法.
* 先使用shutdown, 停止接收新任務並嘗試完成所有已存在任務.
* 如果超時, 則呼叫shutdownNow, 取消在workQueuePending的任務,並中斷所有阻塞函式.
* 如果仍人超時,則強制退出.
* 另對在shutdown時執行緒本身被呼叫中斷做了處理.
*/
public static void gracefulShutdown(ExecutorService pool, int shutdownTimeout, int shutdownNowTimeout,
TimeUnit timeUnit) {
pool.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(shutdownTimeout, timeUnit)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(shutdownNowTimeout, timeUnit)) {
System.err.println("Pool did not terminated");
}
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}

/**
* 直接呼叫shutdownNow的方法, timeout控制.取消在workQueuePending的任務,並中斷所有阻塞函式.
*/
public static void normalShutdown(ExecutorService pool, int timeout, TimeUnit timeUnit) {
try {
pool.shutdownNow();
if (!pool.awaitTermination(timeout, timeUnit)) {
System.err.println("Pool did not terminated");
}
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}

}