##線程池的四種使用方式
1.newSingleThreadExecutor
2.newScheduledThreadPool
**scheduleAtFixedRate如果間隔時間大於任務的執行時間,任務不受執行時間的影響。如果間隔時間小於任務的執行時間,那麼任務執行結束之後,會立馬執行,至此間隔時間就會被打亂。
public static void method_02() {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
executor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
long start = new Date().getTime();
System.out.println("scheduleAtFixedRate 開始執行時間:" +
DateFormat.getTimeInstance().format(new Date()));
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = new Date().getTime();
System.out.println("scheduleAtFixedRate 執行花費時間=" + (end - start) / 1000 + "m");
System.out.println("scheduleAtFixedRate 執行完成時間:" + DateFormat.getTimeInstance().format(new Date()));
System.out.println("======================================");
}
}, 1, 5, TimeUnit.SECONDS);
}
*** scheduleWithFixedDelay的間隔時間不會受任務執行時間長短的影響。
public static void method_03() {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
executor.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
long start = new Date().getTime();
System.out.println("scheduleWithFixedDelay 開始執行時間:" +
DateFormat.getTimeInstance().format(new Date()));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = new Date().getTime();
System.out.println("scheduleWithFixedDelay執行花費時間=" + (end - start) / 1000 + "m");
System.out.println("scheduleWithFixedDelay執行完成時間:"
+ DateFormat.getTimeInstance().format(new Date()));
System.out.println("======================================");
}
}, 1, 2, TimeUnit.SECONDS);
}
3.newFixedThreadPool
newFixedThreadPool的線程數是可以進行控制的,因此我們可以通過控制最大線程來使我們的服務器打到最大的使用率,同事又可以保證及時流量突然增大也不會佔用服務器過多的資源。
###
4.newCachedThreadPool
不足:這種方式雖然可以根據業務場景自動的擴展線程數來處理我們的業務,但是最多需要多少個線程同時處理缺是我們無法控制的;
優點:如果當第二個任務開始,第一個任務已經執行結束,那麼第二個任務會複用第一個任務創建的線程,並不會重新創建新的線程,提高了線程的複用率;