new Thread的弊端如下:
a. 每次new Thread新建對象性能差。
b. 線程缺乏統一管理,可能無限制新建線程,相互之間競爭,及可能佔用過多系統資源導致死機或oom。
c. 缺乏更多功能,如定時執行、定期執行、線程中斷。
相比new Thread,Java提供的四種線程池的好處在於:
a. 重用存在的線程,減少對象創建、消亡的開銷,性能佳。
b. 可有效控制最大併發線程數,提高系統資源的使用率,同時避免過多資源競爭,避免堵塞。
c. 提供定時執行、定期執行、單線程、併發數控制等功能。
2、Java 線程池
Java通過Executors提供四種線程池,分別爲:
newCachedThreadPool創建一個可緩存線程池,如果線程池長度超過處理需要,可靈活回收空閒線程,若無可回收,則新建線程;線程數量無限大,當執行第二個任務時第一個任務已經完成,會複用執行第一個任務的線程,而不用每次新建線程。
newFixedThreadPool 創建一個定長線程池,可控制線程最大併發數,超出的線程會在隊列中等待。
newScheduledThreadPool 創建一個定長線程池,支持定時及週期性任務執行。
newSingleThreadExecutor 創建一個單線程化的線程池,它只會用唯一的工作線程來執行任務,保證所有任務按照指定順序(FIFO, LIFO, 優先級)執行。
public static void main(String[] args) {
ExecutorService executors = Executors.newFixedThreadPool(4);
Future<String> f1 = executors.submit(new TestCallable("Th1"));
Future<String> f2 = executors.submit(new TestCallable("th2"));
Future<?> f3 = executors.submit(t);
Future<?> f4 = executors.submit(t2);
try {
while (true){
if(f1.isDone() && f2.isDone()){
System.out.println("ft:"+f1.get());
System.out.println("ft1:"+f2.get());
break;
}
}
executors.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public class TestCallable implements Callable {
private String tName;
public TestCallable(String tName) {
this.tName = tName;
}
@Override
public Object call() throws Exception {
System.out.println("進入方法!!!"+tName);
int i = 1;
for (;i < 10;i++) {
Thread.sleep(500);
System.out.println(i + "::" + tName);
}
return "tName"+i;
}
}