(一)線程簡介
線程是操作系統(tǒng)調(diào)度的最小單元术唬,每個(gè)線程都擁有自己的計(jì)算器坐求、堆棧和局部變量等屬性讼载,并且能夠訪問共享的內(nèi)存變量趴荸。為什么要使用多線程可以參考Java多線程及線程池簡介儒溉。
線程優(yōu)先級(jí):雖然java線程調(diào)度是系統(tǒng)自動(dòng)完成的,但是我們還是建議系統(tǒng)給某些線程多分配一點(diǎn)執(zhí)行時(shí)間发钝,這個(gè)可以通過線程優(yōu)先級(jí)來完成顿涣。如果我們的程序想干預(yù)線程的調(diào)度過程,最簡單的辦法就是給每個(gè)線程設(shè)定一個(gè)優(yōu)先級(jí)酝豪。線程優(yōu)先級(jí)并不是太靠譜涛碑,原因是java線程是通過映射到系統(tǒng)的原生線程上來實(shí)現(xiàn)的,所以線程調(diào)度最重還是取決于操作系統(tǒng)孵淘,雖然很多操作系統(tǒng)都提供線程優(yōu)先級(jí)概念蒲障,但是并不見得能與java線程優(yōu)先級(jí)一一對(duì)應(yīng)。
線程狀態(tài):Java線程狀態(tài)如下圖所示:
Java線程狀態(tài)變遷如下圖所示:
線程在創(chuàng)建之后瘫证,調(diào)用 start 方法開始運(yùn)行揉阎。當(dāng)線程執(zhí)行 wait 方法之后,線程進(jìn)入等待狀態(tài)背捌。進(jìn)入等待狀態(tài)的線程需要依靠其他線程的通知才能返回運(yùn)行狀態(tài)毙籽,而超時(shí)等待狀態(tài)相當(dāng)于等待狀態(tài)的基礎(chǔ)上增加了超時(shí)限制,也就是超時(shí)時(shí)間到達(dá)時(shí)將會(huì)返回到運(yùn)行狀態(tài)毡庆。當(dāng)線程調(diào)用同步方法時(shí)坑赡,在沒有獲取鎖的情況下,線程將會(huì)進(jìn)入阻塞狀態(tài)么抗。線程在執(zhí)行 Runnable 的 run 方法之后將會(huì)進(jìn)入到終止?fàn)顟B(tài)毅否。注意:Java 將操作系統(tǒng)中的運(yùn)行和就緒兩種狀態(tài)合并為運(yùn)行狀態(tài)。阻塞狀態(tài)是線程阻塞在進(jìn)入synchronized 關(guān)鍵字修飾的方法或代碼塊時(shí)的狀態(tài)蝇刀,但是阻塞在 java.concurrent 包中 Lock 接口的線程狀態(tài)卻是等待狀態(tài)螟加,因?yàn)?java.concurrent 包中 Lock 接口對(duì)于阻塞的實(shí)現(xiàn)均使用了 LockSupport 類中的相關(guān)方法。
(二)啟動(dòng)和終止線程
啟動(dòng)線程:通過調(diào)用線程的start()方法啟動(dòng)線程熊泵,隨著run()方法執(zhí)行完畢仰迁,線程也隨之終止。在構(gòu)建線程時(shí)顽分,最好為每個(gè)線程設(shè)置線程名稱,這樣在進(jìn)行問題排查時(shí)施蜜,可以知道是那個(gè)線程出問題了卒蘸,自定義線程最好能夠起個(gè)名字,如AsyncTask源碼中線程工廠中創(chuàng)建新線程的時(shí)候都會(huì)給線程起一個(gè)“AsyncTask #mCount”的名字,其中mCount就是我們?cè)贘ava并發(fā)機(jī)制的底層實(shí)現(xiàn)講到的原子操作類缸沃,原子操作類在并發(fā)操作的時(shí)候是線程安全的恰起,原子操作類是基于CAS來實(shí)現(xiàn)。
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
理解中斷:中斷可以理解為線程的一個(gè)標(biāo)志位屬性趾牧,它標(biāo)識(shí)一個(gè)運(yùn)行中的線程是否被其它線程進(jìn)行了中斷操作检盼。中斷好比其他線程對(duì)該線程打了招呼,其它線程通過調(diào)用該線程的interrupt()方法對(duì)其進(jìn)行中斷操作翘单。
過期的suspend()吨枉、resume()和stop()操作:如果把播放音樂比作一個(gè)線程的運(yùn)行,那么對(duì)音樂播放做出的暫停哄芜、恢復(fù)和停止操作對(duì)應(yīng)在線程Thread的API就是suspend()貌亭、resume()和stop()。不建議使用的原因:suspend()方法調(diào)用后认臊,線程不會(huì)釋放已經(jīng)占有的資源(比如鎖)圃庭,而是占著資源進(jìn)入睡眠狀態(tài),這樣容易引起死鎖失晴。同樣剧腻,stop()方法在終結(jié)一個(gè)線程時(shí)不會(huì)保證線程的資源正常釋放,通常沒有給予線程完成資源釋放的工作機(jī)會(huì)涂屁,因此會(huì)導(dǎo)致程序可能工作在不確定的狀態(tài)下恕酸。目前暫停和恢復(fù)操作用等待/通知機(jī)制來替代。
安全的終止線程:中斷是線程的一個(gè)標(biāo)識(shí)位胯陋,而中斷操作是一種簡單的線程交互方式蕊温,而這種交互方式最適合用來取消或者停止任務(wù),而除了中斷以外遏乔,還可以利用一個(gè)boolean變量來控制是否需要停止任務(wù)并終止該線程义矛。還有就是run方法執(zhí)行完畢之后線程也就終止了。安全終止線程的三種方法:1.run方法運(yùn)行完畢盟萨;2.使用中斷標(biāo)志終止線程凉翻;3.使用一個(gè)boolean變量來終止線程。示例代碼及日志如下:
private void stopThreadTest(){
try {
Thread thread = new Thread(new Runner(),"TestThread1");
thread.start();
Thread.sleep(100);
thread.interrupt();
Runner runner = new Runner();
Thread thread1 = new Thread(runner,"TestThread2");
thread1.start();
Thread.sleep(100);
runner.cancelThread();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static class Runner implements Runnable{
private int i;
private volatile boolean on = true;
@Override
public void run() {
Log.d("StopThread", "threadName:" + Thread.currentThread().getName() + " start");
while (on && !Thread.interrupted()){
i++;
}
//打印對(duì)應(yīng)的線程名稱
Log.d("StopThread", "threadName:" + Thread.currentThread().getName() + " end");
}
public void cancelThread(){
on = false;
}
}
打印日志:
10:47:08.018 21231-21359/ D/StopThread: threadName:TestThread1 start
10:47:08.118 21231-21359/ D/StopThread: threadName:TestThread1 end
10:47:08.118 21231-21360/ D/StopThread: threadName:TestThread2 start
10:47:08.218 21231-21360/ D/StopThread: threadName:TestThread2 end
主線程通過中斷操作或者cancel()方法均可使線程終止捻激,這種通過標(biāo)志位或者中斷操作的方法能夠使線程在終止時(shí)有機(jī)會(huì)去清理資源制轰,而不是武斷的將線程終止,因此這種終止線程的做法更加安全和優(yōu)雅胞谭。
(三)線程間通信
1.volatile 和 synchronized 關(guān)鍵字
volatile 與 synchronized 保證可見性垃杖,可見性如果用內(nèi)存模型來闡述,那就是在變量的寫的時(shí)候丈屹,把把該變量同步到主內(nèi)存调俘,其他線程通過嗅探主內(nèi)存的該變量值是否變化伶棒,在變化的時(shí)候更新自己的工作內(nèi)存,這樣就完成了線程之間的交互彩库。
2.等待/通知機(jī)制
應(yīng)用場(chǎng)景:一個(gè)線程修改了一個(gè)對(duì)象的值肤无,而另一個(gè)線程感知到了變化,然后進(jìn)行響應(yīng)的操作骇钦,這個(gè)過程開始于一個(gè)線程宛渐,而最終執(zhí)行又是另一個(gè)線程。這種模式隔離了做什么和怎么做眯搭,在功能成眠實(shí)現(xiàn)了解耦窥翩,Java通過內(nèi)置的等待/通知機(jī)制為這種場(chǎng)景提供了很好的解決方案。等待/通知的相關(guān)方法是任意Java對(duì)象都具備的坦仍,因?yàn)檫@些方法被定義在所有對(duì)象的超類 java.lang.Object上鳍烁,方法和描述如下圖所示:
等待 / 通知機(jī)制,是指一個(gè)線程 A 調(diào)用了對(duì)象 O 的 wait 方法進(jìn)入等待狀態(tài)繁扎,而另外一個(gè)線程 B 調(diào)用了對(duì)象 O 的 notify 或者 notifyAll 方法幔荒,線程 A 收到通知后從對(duì)象 O 的 wait 方法返回,進(jìn)而執(zhí)行后續(xù)操作梳玫。上訴兩個(gè)線程通過對(duì)象 O 完成交互爹梁,而對(duì)象上的 wait 方法和notify / notifyAll 的關(guān)系就如同開關(guān)信號(hào)一樣,用來完成等待方和通知方之間的交互工作提澎。使用示例如下:
static boolean flag = true;
static Object lock = new Object();
private static final String TAGT = "WaitNotifyTest";
private static final int SLEEP_TIME = 1000;
private void testWaitNotify(){
try {
Thread waitThread = new Thread(new WaitRunner(),"WaitThread");
waitThread.start();
Thread.sleep(SLEEP_TIME);
Thread notifyThread = new Thread(new NotifyRunner(),"NotifyThread");
notifyThread.start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class WaitRunner implements Runnable{
@Override
public void run() {
//First:WaitThread get monitor
synchronized (lock){
while (flag){
Log.d(TAGT, "threadName:" + Thread.currentThread().getName() + "- call object.wait()");
try {
//Second: object.wait & release monitor
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//Third: util other thread call lock,notify,WaitThread do something when condition satisfied
if(!flag){
Log.d(TAGT, "WaitThread do something");
}
}
}
}
static class NotifyRunner implements Runnable{
@Override
public void run() {
try {
//First: NotifyThread get monitor
synchronized (lock){
//Second : object.notify(),notify() do not release monitor until this method complete
Log.d(TAGT, "theadName: " + Thread.currentThread().getName() + "- call object.notify()");
lock.notifyAll();
flag = false;
Thread.sleep(SLEEP_TIME);
}
synchronized (lock){
Thread.sleep(SLEEP_TIME);
Log.d(TAGT, "theadName: " + Thread.currentThread().getName() + "- notifyThread end");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
打印日志如下:
D/WaitNotifyTest: threadName:WaitThread- call object.wait()
D/WaitNotifyTest: theadName: NotifyThread- call object.notify()
D/WaitNotifyTest: theadName: NotifyThread- notifyThread end
D/WaitNotifyTest: WaitThread do something
在使用以上方法需要注意幾點(diǎn):
(1)使用 wait姚垃、notify、notifyAll 時(shí)需要先對(duì)調(diào)用對(duì)象加鎖
(2)調(diào)用 wait 方法后盼忌,線程狀態(tài)由 RUNNING 變?yōu)?WAITING积糯,并將當(dāng)前線程放置到對(duì)象的等待隊(duì)列
(3)notify 或 notifyAll 方法調(diào)用之后,等待線程依舊不會(huì)從 wait 返回谦纱,需要調(diào)用 notify 或 notifyAll 的線程釋放鎖之后看成,等待線程才有機(jī)會(huì)從 wait 方法
(4)notify 方法將等待隊(duì)列中的一個(gè)等待線程從等待隊(duì)列中移到同步隊(duì)列中,而 notifyAll 方法則是將等待隊(duì)列中所有的線程全部移到同步隊(duì)列跨嘉,被移動(dòng)的線程狀態(tài)由 WAITING 變?yōu)?BLOCKED
(5)從 wait 方法返回的前提是獲得了調(diào)用對(duì)象的鎖
下圖描述了上述示例
從上圖可知川慌,WaitThread首先獲取對(duì)象的鎖,然后調(diào)用對(duì)象的wait()方法祠乃,從而放棄了鎖并進(jìn)入對(duì)象的等待隊(duì)列WaitQueue中梦重,進(jìn)入等待狀態(tài)。由于WaitThread釋放了對(duì)象的鎖亮瓷,NotifyThread隨后獲取了對(duì)象的鎖琴拧,并調(diào)用對(duì)象的notify()方法,將WaitThread從WaitQueue移到SynchronizedQueue中寺庄,此時(shí)WaitThread的狀態(tài)變?yōu)樽枞麪顟B(tài)艾蓝,NotifyThread釋放鎖之后力崇,WaitThread再次獲取到鎖并從wait()方法返回繼續(xù)執(zhí)行斗塘。
等待/通知經(jīng)典范式
該范式分為兩部分赢织,分別針對(duì)等待放(消費(fèi)者)和通知方(生產(chǎn)者)
等待方遵循如下原則:
(1)獲取對(duì)象的鎖;
(2)如果條件不滿足馍盟,那么調(diào)用對(duì)象的wait()方法于置,被通知后仍要檢查條件。
(3)條件滿足則執(zhí)行對(duì)應(yīng)的邏輯贞岭。
對(duì)應(yīng)偽代碼如下:
sychronized(對(duì)象){
while(條件不滿足){
對(duì)象.wait();
}
對(duì)應(yīng)的處理邏輯
}
通知方遵循的如下原則:
(1)獲取對(duì)象的鎖八毯;
(2)改變條件;
(3)通知所有等待在對(duì)象上的線程瞄桨;
對(duì)應(yīng)偽代碼如下:
sychronized(對(duì)象){
改變條件
對(duì)象.notifyAll();
}
3.管道輸入/ 輸出流
管道輸入 / 輸出流和普通的文件輸入 / 輸出流或者網(wǎng)絡(luò)輸入 / 輸出流不同之處在于话速,它主要用于線程之間的數(shù)據(jù)傳輸,而傳輸?shù)拿浇闉閮?nèi)存芯侥。管道輸入 / 輸出流主要包括了如下四種具體實(shí)現(xiàn):PipedOutputStream泊交、PipedInputStream、PipedReader柱查、PipedWriter廓俭,前兩種面向字節(jié),而后兩種面向字符唉工。
public class PipedDemo {
public static void main(String[] args) throws IOException {
PipedReader pipedReader = new PipedReader();
PipedWriter pipedWriter = new PipedWriter();
//將輸入輸出流進(jìn)行鏈接研乒,否則會(huì)拋出 IOException
pipedWriter.connect(pipedReader);
Thread printThread = new Thread(new PrintRunnable(pipedReader));
printThread.start();
int receive = 0;
try {
while ((receive = System.in.read()) != -1) {
pipedWriter.write(receive);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
pipedWriter.close();
}
}
static class PrintRunnable implements Runnable {
private PipedReader pipedReader;
public PrintRunnable(PipedReader pipedReader) {
this.pipedReader = pipedReader;
}
@Override
public void run() {
int receive = 0;
try {
while ((receive = pipedReader.read()) != -1) {
System.out.println("輸出:" + (char) receive);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Demo
* 輸出:D
* 輸出:e
* 輸出:m
* 輸出:o
* 輸出
*/
4.Thread.join() 的使用
如果一個(gè)線程 A 執(zhí)行了 thread.join() 語句,其含義是:當(dāng)前線程 A 等待 thread 線程終止之后才從 thread.join() 返回淋硝。線程 Thread 除了提供 join 方法之外雹熬,還提供了 join(long millis)等兩個(gè)具備超時(shí)特性的方法。這兩個(gè)超時(shí)方法表示谣膳,如果線程 thread 在給定的超時(shí)時(shí)間里沒有終止竿报,那么將會(huì)從該超時(shí)方法中返回。
public class JoinDemo {
public static void main(String[] args) {
Thread previous = Thread.currentThread();
for (int i = 0; i < 10; i++) {
//每個(gè)線程擁有前一個(gè)線程的引用参歹,需要等待前一個(gè)線程終止仰楚,才能從等待中返回
Thread thread=new Thread(new MyRunnable(previous),String.valueOf(i));
thread.start();
previous=thread;
}
}
static class MyRunnable implements Runnable{
private Thread thread;
public MyRunnable(Thread thread) {
this.thread = thread;
}
@Override
public void run() {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" terminate ");
}
}
}
/**輸出:
* 0 terminate
* 1 terminate
* 2 terminate
* 3 terminate
* 4 terminate
* 5 terminate
* 6 terminate
* 7 terminate
* 8 terminate
* 9 terminate
*/
從輸出可以看出,每個(gè)線程終止的前提是前驅(qū)線程的終止犬庇,每個(gè)線程等待前驅(qū)線程終止后僧界,才從 join 方法返回,這里涉及了等待 / 通知機(jī)制(等待前驅(qū)線程結(jié)束臭挽,接受前驅(qū)線程結(jié)束的通知)捂襟。當(dāng)線程終止時(shí),會(huì)調(diào)用線程自身的 notifyAll 方法欢峰,會(huì)通知所有等待在該線程對(duì)象上的線程葬荷。
參考資料
《Java并發(fā)編程的藝術(shù)》
《深入理解JVM》