一.線程生命周期
線程的5種狀態(tài):
新建(New) ,就緒(Runnable)悔政,運行(Running)晚吞,阻塞(Blocked),死亡(Dead)
二.線程池
- 為什么要使用線程池:
(1).提高性能
系統(tǒng)啟動一個新線程的成本是比較高的谋国,而使用線程池避免了頻繁的創(chuàng)建和銷毀線程槽地,可以很好地提高性能。
線程池在系統(tǒng)啟動時即創(chuàng)建大量空閑的線程,程序?qū)⒁粋€Runnable對象或Callable對象傳給線程池捌蚊,線程池就會自動
啟動一個線程來執(zhí)行它們的run()或call()方法集畅,當run()或call()方法執(zhí)行結(jié)束后,該線程并不會死亡缅糟,而是再次
返回線程池中成為空閑狀態(tài)挺智,等待執(zhí)行下一個對象的run()或call()方法。
(2).控制線程數(shù)量
使用線程池還可以有效地控制系統(tǒng)中并發(fā)線程的數(shù)量窗宦,當系統(tǒng)中包含大量并發(fā)線程時赦颇,會導(dǎo)致系統(tǒng)性能劇烈下降,
甚至導(dǎo)致JVM崩潰赴涵,而線程池的最大線程數(shù)參數(shù)可以控制系統(tǒng)中并發(fā)線程數(shù)量媒怯。
- 關(guān)閉線程池 shutdown()方法
shutdown() :執(zhí)行完已提交的任務(wù)后關(guān)閉線程池
shutdownNow() :停止所有正在執(zhí)行的任務(wù),并關(guān)閉線程池
- 使用線程池的步驟:
(1)調(diào)用Executors類的靜態(tài)工廠方法創(chuàng)建一個ExecutorService對象髓窜,該對象代表一個線程池
(2)創(chuàng)建Runnable實現(xiàn)類或Callable實現(xiàn)類的實例扇苞,作為線程執(zhí)行任務(wù)
(3)調(diào)用ExecutorService對象的submit()方法來提交Runnable實例或Callable實例
(4)當不想提交任何任務(wù)時,調(diào)用ExecutorService對象的shutdown()方法來關(guān)閉線程池
public class ThreadPoolTest {
public static void main(String[] args) {
//1.創(chuàng)建線程池
ExecutorService pool = Executors.newFixedThreadPool(6);
//2.創(chuàng)建要執(zhí)行的線程任務(wù)
MyThread mt1 = new MyThread();
MyThread mt2 = new MyThread();
//3.提交線程任務(wù)
pool.submit(mt1);
pool.submit(mt2);
//4.關(guān)閉線程池
pool.shutdown();
}
}
class MyThread implements Runnable {
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("MyThread--" + "i");
}
}
}
4.API
- 所有與線程池有關(guān)的操作放在java.util.concurrent包中
- Executor接口寄纵,ExecutorService接口杨拐,Executors類及相關(guān)方法
- 創(chuàng)建線程池的方法:
newSingleThreadExecutor() :創(chuàng)建一個只有單線程的線程池,它相當于調(diào)用newFixedThreadPool()
方法時傳入?yún)?shù)為1
newFixedThreadPool(int nThreads) :創(chuàng)建具有固定線程數(shù)的線程池擂啥,每提交一個任務(wù)就創(chuàng)建一個線程,
直到最大值帆阳,線程池一旦達到最大值就會保持不變
newCachedThreadPool() :創(chuàng)建一個可緩存的線程池哺壶,它會根據(jù)需要創(chuàng)建線程,并回收空閑線程蜒谤,可以
說是一個動態(tài)的可大可小的線程池
以上3個方法返回ExecutorService對象山宾,該對象代表一個線程池,它是即時執(zhí)行的
newScheduledThreadPool(int corePoolSize) :創(chuàng)建具有指定線程數(shù)的線程池鳍徽,并延時執(zhí)行
newSingleThreadScheduledExecutor() :創(chuàng)建只有一個線程的線程池资锰,延遲執(zhí)行
*以上2個方法返回一個ScheduledExecutorService線程池,它是ExecutorService的子類阶祭,延時執(zhí)行的