概述
- 線程是進(jìn)程的一個執(zhí)行單元排拷,是CPU任務(wù)調(diào)度的基本單位斤蔓。一個進(jìn)程可以包含多個線程粟按,同一個進(jìn)程下的所有線程共享改進(jìn)程的所有資源
生命周期
EDAC1216-251F-4493-BEA8-2B09CF551227.png
新建狀態(tài):創(chuàng)建實(shí)例
就緒狀態(tài):等待CPU分配時間
運(yùn)行狀態(tài):執(zhí)行中中捆,獲得CPU資源漂彤。
阻塞狀態(tài):釋放cpu資源雾消,在某些條件下回到就緒狀態(tài),調(diào)用sleep方法進(jìn)入阻塞狀態(tài)显歧,釋放cpu資源仪或,不會釋放鎖,調(diào)用wait方法士骤,在釋放資源的同時范删,也會釋放鎖。
死亡狀態(tài):線程執(zhí)行完畢拷肌,或者stop線程到旦。
優(yōu)點(diǎn)
- 劃分尺度小,執(zhí)行開銷小巨缘,提高并行效率
- 共享內(nèi)存添忘,提高資源利用率和執(zhí)行效率
缺點(diǎn)
- 沒有單獨(dú)的地址空間,不能獨(dú)立運(yùn)行若锁,無法對資源進(jìn)行管理搁骑。
創(chuàng)建
創(chuàng)建線程的四種方式:
-
繼承Thread類
public class ThreadDemo extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
System.out.println("創(chuàng)建線程的第一種方式");
}
}
ThreadDemo threadDemo = new ThreadDemo();
threadDemo.setName("thread-demo");
//1標(biāo)準(zhǔn)的啟動方式
threadDemo.start();
//2、調(diào)用類的方法的啟動方式
threadDemo.run();
start()和run()的區(qū)別:
start()方法會創(chuàng)建一個新的線程又固,執(zhí)行run方法仲器。
run()方法,類的方法調(diào)用是在主線程上執(zhí)行仰冠。
可通過在Thread.currentThread().getName()查看執(zhí)行線程名
-
繼承runable接口
public class RunableDemo implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
System.out.println("創(chuàng)建線程的第二種方法");
}
}
Thread thread = new Thread(new RunableDemo());
thread.start();
推薦使用這種方式乏冀,有利于在多繼承的情況下的代碼擴(kuò)展
-
有返回值的創(chuàng)建線程的callable方式
public class CallableDemo implements Callable {
@Override
public Integer call() throws Exception {
System.out.println(Thread.currentThread().getName());
System.out.println("創(chuàng)建線程的第二種方法");
return 1;
}
}
CallableDemo callableDemo = new CallableDemo();
FutureTask futureTask = new FutureTask(callableDemo);
Thread callThread = new Thread(futureTask,"返回值");
callThread.start();
futureTask.get();
以繼承callable接口創(chuàng)建線程,可以有返回值洋只,通過cas原理把數(shù)據(jù)set到futureTask對象中辆沦,調(diào)用get方式會使程序進(jìn)入阻塞狀態(tài),直到線程執(zhí)行完畢拿到返回值识虚。
-
線程池
E120FD3A-8122-44C4-B5E9-B9B8447A8298.png
- 頂層接口Executor肢扯,內(nèi)部包含一個execute方法,入?yún)⑹莻€Runable對象担锤。
- ThreadPoolExecutor鹃彻,線程池定義類
* corePoolSize 核心線程數(shù)
* maximumPoolSize 最大線程數(shù)
* keepAliveTime 空閑時間
* unit 單位
* workQueue 工作隊(duì)列,用于管理任務(wù)
* threadFactory 線程工廠類
* defaultHandler 默認(rèn)處理方法,工作隊(duì)列無空閑的情況下的處理辦法妻献。 - Executors 創(chuàng)建線程池的工具類蛛株,tips:工具類一般都是以s結(jié)尾,例:Collections育拨、Arrays
線程池種類
- 單一線程執(zhí)行任務(wù)谨履,F(xiàn)IFO機(jī)制,保證任務(wù)的有序性,線程池核心線程和最大線程數(shù)均為1熬丧,永不過期笋粟,以一個鏈表隊(duì)列管理任務(wù)有序執(zhí)行。源碼結(jié)構(gòu):
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
- 固定大小的線程池析蝴,當(dāng)有新的任務(wù)進(jìn)來害捕,就會創(chuàng)建一個新的線程去執(zhí)行,任務(wù)執(zhí)行完畢闷畸,線程并不會被回收尝盼,而是變成空閑線程,等待執(zhí)行下次任務(wù)佑菩,會占用一部分資源盾沫,但是節(jié)約了線程重復(fù)創(chuàng)建和銷毀的開銷。
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
- 不固定大小的線程池殿漠,創(chuàng)建線程最大數(shù)為Integer.MAX_VALUE,而且可以回收空閑線程赴精。
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
- 定時任務(wù)線程,定時任務(wù)绞幌,支持周期性工作蕾哟。
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}