基於Java回顧之多線程詳解

來源:互聯網
上載者:User

線程是作業系統啟動並執行基本單位,它被封裝在進程中,一個進程可以包含多個線程。即使我們不手動創造線程,進程也會有一個預設的線程在運行。

對於JVM來說,當我們編寫一個單線程的程式去運行時,JVM中也是有至少兩個線程在運行,一個是我們建立的程式,一個是記憶體回收。

線程基本資料

我們可以通過Thread.currentThread()方法擷取當前線程的一些資訊,並對其進行修改。

我們來看以下代碼:

複製代碼 代碼如下:查看並修改當前線程的屬性
String name = Thread.currentThread().getName();
int priority = Thread.currentThread().getPriority();
String groupName = Thread.currentThread().getThreadGroup().getName();
boolean isDaemon = Thread.currentThread().isDaemon();
System.out.println("Thread Name:" + name);
System.out.println("Priority:" + priority);
System.out.println("Group Name:" + groupName);
System.out.println("IsDaemon:" + isDaemon);

Thread.currentThread().setName("Test");
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
name = Thread.currentThread().getName();
priority = Thread.currentThread().getPriority();
groupName = Thread.currentThread().getThreadGroup().getName();
isDaemon = Thread.currentThread().isDaemon();
System.out.println("Thread Name:" + name);
System.out.println("Priority:" + priority);

其中列出的屬性說明如下:

GroupName,每個線程都會預設在一個線程組裡,我們也可以顯式的建立線程組,一個線程組中也可以包含子線程組,這樣線程和線程組,就構成了一個樹狀結構。

Name,每個線程都會有一個名字,如果不顯式指定,那麼名字的規則是“Thread-xxx”。

Priority,每個線程都會有自己的優先順序,JVM對優先順序的處理方式是“搶佔式”的。當JVM發現優先順序高的線程時,馬上運行該線程;對於多個優先順序相等的線程,JVM對其進行輪詢處理。Java的線程優先順序從1到10,預設是5,Thread類定義了2個常量:MIN_PRIORITY和MAX_PRIORITY來表示最高和最低優先順序。

我們可以看下面的代碼,它定義了兩個不同優先順序的線程:

複製代碼 代碼如下:線程優先順序樣本
public static void priorityTest()
{
Thread thread1 = new Thread("low")
{
public void run()
{
for (int i = 0; i < 5; i++)
{
System.out.println("Thread 1 is running.");
}
}
};

Thread thread2 = new Thread("high")
{
public void run()
{
for (int i = 0; i < 5; i++)
{
System.out.println("Thread 2 is running.");
}
}
};

thread1.setPriority(Thread.MIN_PRIORITY);
thread2.setPriority(Thread.MAX_PRIORITY);
thread1.start();
thread2.start();
}

從運行結果可以看出,是高優先順序線程運行完成後,低優先順序線程才運行。
isDaemon,這個屬性用來控制父子線程的關係,如果設定為true,當父線程結束後,其下所有子線程也結束,反之,子線程的生命週期不受父線程影響。
我們來看下面的例子:複製代碼 代碼如下:IsDaemon 樣本
public static void daemonTest()
{
Thread thread1 = new Thread("daemon")
{
public void run()
{
Thread subThread = new Thread("sub")
{
public void run()
{
for(int i = 0; i < 100; i++)
{
System.out.println("Sub Thread Running " + i);
}
}
};
subThread.setDaemon(true);
subThread.start();
System.out.println("Main Thread end.");
}
};

thread1.start();
}

上面代碼的運行結果,在和刪除subThread.setDaemon(true);後對比,可以發現後者運行過程中子線程會完成執行後再結束,而前者中,子線程很快就結束了。

如何建立線程

上面的內容,都是示範預設線程中的一些資訊,那麼應該如何建立線程呢?在Java中,我們有3種方式可以用來建立線程。

Java中的線程要麼繼承Thread類,要麼實現Runnable介面,我們一一道來。

使用內部類來建立線程

我們可以使用內部類的方式來建立線程,過程是聲明一個Thread類型的變數,並重寫run方法。範例程式碼如下:

複製代碼 代碼如下:使用內部類建立線程
public static void createThreadByNestClass()
{
Thread thread = new Thread()
{
public void run()
{
for (int i =0; i < 5; i++)
{
System.out.println("Thread " + Thread.currentThread().getName() + " is running.");
}
System.out.println("Thread " + Thread.currentThread().getName() + " is finished.");
}
};
thread.start();
}

繼承Thread以建立線程

我們可以從Thread中派生一個類,重寫其run方法,這種方式和上面相似。範例程式碼如下:

複製代碼 代碼如下:派生Thread類以建立線程
class MyThread extends Thread
{
public void run()
{
for (int i =0; i < 5; i++)
{
System.out.println("Thread " + Thread.currentThread().getName() + " is running.");
}
System.out.println("Thread " + Thread.currentThread().getName() + " is finished.");
}
}

public static void createThreadBySubClass()
{
MyThread thread = new MyThread();
thread.start();
}

實現Runnable介面以建立線程

我們可以定義一個類,使其實現Runnable介面,然後將該類的執行個體作為構建Thread變數建構函式的參數。範例程式碼如下:

複製代碼 代碼如下:實現Runnable介面以建立線程
class MyRunnable implements Runnable
{
public void run()
{
for (int i =0; i < 5; i++)
{
System.out.println("Thread " + Thread.currentThread().getName() + " is running.");
}
System.out.println("Thread " + Thread.currentThread().getName() + " is finished.");
}
}

public static void createThreadByRunnable()
{
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}

上述3種方式都可以建立線程,而且從範例程式碼上看,線程執行的功能是一樣的,那麼這三種建立方式有什麼不同呢?

這涉及到Java中多線程的運行模式,對於Java來說,多線程在運行時,有“多個物件多線程”和“單對象多線程”的區別:

多個物件多線程,程式在運行過程中建立多個線程對象,每個對象上運行一個線程。
單對象多線程,程式在運行過程中建立一個線程對象,在其上運行多個線程。

顯然,從線程同步和調度的角度來看,多個物件多線程要簡單一些。上述3種線程建立方式,前兩種都屬於“多個物件多線程”,第三種既可以使用“多個物件多線程”,也可以使用“單對象單線程”。

我們來看下面的範例程式碼,裡面會用到Object.notify方法,這個方法會喚醒對象上的一個線程;而Object.notifyAll方法,則會喚醒對象上的所有線程。

複製代碼 代碼如下:notify樣本
public class NotifySample {

public static void main(String[] args) throws InterruptedException
{
notifyTest();
notifyTest2();
notifyTest3();
}

private static void notifyTest() throws InterruptedException
{
MyThread[] arrThreads = new MyThread[3];
for (int i = 0; i < arrThreads.length; i++)
{
arrThreads[i] = new MyThread();
arrThreads[i].id = i;
arrThreads[i].setDaemon(true);
arrThreads[i].start();
}
Thread.sleep(500);
for (int i = 0; i < arrThreads.length; i++)
{
synchronized(arrThreads[i])
{
arrThreads[i].notify();
}
}
}

private static void notifyTest2() throws InterruptedException
{
MyRunner[] arrMyRunners = new MyRunner[3];
Thread[] arrThreads = new Thread[3];
for (int i = 0; i < arrThreads.length; i++)
{
arrMyRunners[i] = new MyRunner();
arrMyRunners[i].id = i;
arrThreads[i] = new Thread(arrMyRunners[i]);
arrThreads[i].setDaemon(true);
arrThreads[i].start();
}
Thread.sleep(500);
for (int i = 0; i < arrMyRunners.length; i++)
{
synchronized(arrMyRunners[i])
{
arrMyRunners[i].notify();
}
}
}

private static void notifyTest3() throws InterruptedException
{
MyRunner runner = new MyRunner();
Thread[] arrThreads = new Thread[3];
for (int i = 0; i < arrThreads.length; i++)
{
arrThreads[i] = new Thread(runner);
arrThreads[i].setDaemon(true);
arrThreads[i].start();
}
Thread.sleep(500);

synchronized(runner)
{
runner.notifyAll();
}
}
}

class MyThread extends Thread
{
public int id = 0;
public void run()
{
System.out.println("第" + id + "個線程準備休眠5分鐘。");
try
{
synchronized(this)
{
this.wait(5*60*1000);
}
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
System.out.println("第" + id + "個線程被喚醒。");
}
}

class MyRunner implements Runnable
{
public int id = 0;
public void run()
{
System.out.println("第" + id + "個線程準備休眠5分鐘。");
try
{
synchronized(this)
{
this.wait(5*60*1000);
}
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
System.out.println("第" + id + "個線程被喚醒。");
}

}

範例程式碼中,notifyTest()和notifyTest2()是“多個物件多線程”,儘管notifyTest2()中的線程實現了Runnable介面,但是它裡面定義Thread數組時,每個元素都使用了一個新的Runnable執行個體。notifyTest3()屬於“單對象多線程”,因為我們只定義了一個Runnable執行個體,所有的線程都會使用這個執行個體。

notifyAll方法適用於“單對象多線程”的情景,因為notify方法只會隨機喚醒對象上的一個線程。

線程的狀態切換

對於線程來講,從我們建立它一直到線程運行結束,在這個過程中,線程的狀態可能是這樣的:

建立:已經有Thread執行個體了, 但是CPU還有為其分配資源和時間片。
就緒:線程已經獲得了運行所需的所有資源,只等CPU進行時間調度。
運行:線程位於當前CPU時間片中,正在執行相關邏輯。
休眠:一般是調用Thread.sleep後的狀態,這時線程依然持有運行所需的各種資源,但是不會被CPU調度。
掛起:一般是調用Thread.suspend後的狀態,和休眠類似,CPU不會調度該線程,不同的是,這種狀態下,線程會釋放所有資源。
死亡:線程運行結束或者調用了Thread.stop方法。

下面我們來示範如何進行線程狀態切換,首先我們會用到下面方法:

Thread()或者Thread(Runnable):構造線程。
Thread.start:啟動線程。
Thread.sleep:將線程切換至休眠狀態。
Thread.interrupt:中斷線程的執行。
Thread.join:等待某線程結束。
Thread.yield:剝奪線程在CPU上的執行時間片,等待下一次調度。
Object.wait:將Object上所有線程鎖定,直到notify方法才繼續運行。
Object.notify:隨機喚醒Object上的1個線程。
Object.notifyAll:喚醒Object上的所有線程。

下面,就是示範時間啦!!!

線程等待與喚醒

這裡主要使用Object.wait和Object.notify方法,請參見上面的notify執行個體。需要注意的是,wait和notify都必須針對同一個對象,當我們使用實現Runnable介面的方式來建立線程時,應該是在Runnable對象而非Thread對象上使用這兩個方法。

線程的休眠與喚醒

複製代碼 代碼如下:Thread.sleep執行個體
public class SleepSample {

public static void main(String[] args) throws InterruptedException
{
sleepTest();
}

private static void sleepTest() throws InterruptedException
{
Thread thread = new Thread()
{
public void run()
{
System.out.println("線程 " + Thread.currentThread().getName() + "將要休眠5分鐘。");
try
{
Thread.sleep(5*60*1000);
}
catch(InterruptedException ex)
{
System.out.println("線程 " + Thread.currentThread().getName() + "休眠被中斷。");
}
System.out.println("線程 " + Thread.currentThread().getName() + "休眠結束。");
}
};
thread.setDaemon(true);
thread.start();
Thread.sleep(500);
thread.interrupt();
}

}

線程在休眠過程中,我們可以使用Thread.interrupt將其喚醒,這時線程會拋出InterruptedException。

線程的終止

雖然有Thread.stop方法,但該方法是不被推薦使用的,我們可以利用上面休眠與喚醒的機制,讓線程在處理IterruptedException時,結束線程。

複製代碼 代碼如下:Thread.interrupt樣本
public class StopThreadSample {

public static void main(String[] args) throws InterruptedException
{
stopTest();
}

private static void stopTest() throws InterruptedException
{
Thread thread = new Thread()
{
public void run()
{
System.out.println("線程運行中。");
try
{
Thread.sleep(1*60*1000);
}
catch(InterruptedException ex)
{
System.out.println("線程中斷,結束線程");
return;
}
System.out.println("線程正常結束。");
}
};
thread.start();
Thread.sleep(500);
thread.interrupt();
}
}

線程的同步等待

當我們在主線程中建立了10個子線程,然後我們期望10個子線程全部結束後,主線程在執行接下來的邏輯,這時,就該Thread.join登場了。

複製代碼 代碼如下:Thread.join樣本
public class JoinSample {

public static void main(String[] args) throws InterruptedException
{
joinTest();
}

private static void joinTest() throws InterruptedException
{
Thread thread = new Thread()
{
public void run()
{
try
{
for(int i = 0; i < 5; i++)
{
System.out.println("線程在運行。");
Thread.sleep(1000);
}
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
}
};
thread.setDaemon(true);
thread.start();
Thread.sleep(1000);
thread.join();
System.out.println("主線程正常結束。");
}
}

我們可以試著將thread.join();注釋或者刪除,再次運行程式,就可以發現不同了。

線程間通訊

我們知道,一個進程下面的所有線程是共用記憶體空間的,那麼我們如何在不同的線程之間傳遞訊息呢?在回顧 Java I/O時,我們談到了PipedStream和PipedReader,這裡,就是它們發揮作用的地方了。

下面的兩個樣本,功能完全一樣,不同的是一個使用Stream,一個使用Reader/Writer。

複製代碼 代碼如下:PipeInputStream/PipedOutpueStream 樣本
public static void communicationTest() throws IOException, InterruptedException
{
final PipedOutputStream pos = new PipedOutputStream();
final PipedInputStream pis = new PipedInputStream(pos);

Thread thread1 = new Thread()
{
public void run()
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try
{
while(true)
{
String message = br.readLine();
pos.write(message.getBytes());
if (message.equals("end")) break;
}
br.close();
pos.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
};

Thread thread2 = new Thread()
{
public void run()
{
byte[] buffer = new byte[1024];
int bytesRead = 0;
try
{
while((bytesRead = pis.read(buffer, 0, buffer.length)) != -1)
{
System.out.println(new String(buffer));
if (new String(buffer).equals("end")) break;
buffer = null;
buffer = new byte[1024];
}
pis.close();
buffer = null;
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
};

thread1.setDaemon(true);
thread2.setDaemon(true);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
}

複製代碼 代碼如下:PipedReader/PipedWriter 樣本
private static void communicationTest2() throws InterruptedException, IOException
{
final PipedWriter pw = new PipedWriter();
final PipedReader pr = new PipedReader(pw);
final BufferedWriter bw = new BufferedWriter(pw);
final BufferedReader br = new BufferedReader(pr);

Thread thread1 = new Thread()
{
public void run()
{

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try
{
while(true)
{
String message = br.readLine();
bw.write(message);
bw.newLine();
bw.flush();
if (message.equals("end")) break;
}
br.close();
pw.close();
bw.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
};

Thread thread2 = new Thread()
{
public void run()
{

String line = null;
try
{
while((line = br.readLine()) != null)
{
System.out.println(line);
if (line.equals("end")) break;
}
br.close();
pr.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
};

thread1.setDaemon(true);
thread2.setDaemon(true);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.