第一篇:Java回顧之I/O
第二篇:Java回顧之網絡通信
在這篇文章里,我們關注多線程。多線程是一個復雜的話題,包含了很多內容,這篇文章主要關注線程的基本屬性、如何創建線程、線程的狀態切換以及線程通信,我們把線程同步的話題留到下一篇文章中。
線程是操作系統運行的基本單位,它被封裝在進程中,一個進程可以包含多個線程。即使我們不手動創造線程,進程也會有一個默認的線程在運行。
對於JVM來說,當我們編寫一個單線程的程序去運行時,JVM中也是有至少兩個線程在運行,一個是我們創建的程序,一個是垃圾回收。
線程基本信息
我們可以通過Thread.currentThread()方法獲取當前線程的一些信息,並對其進行修改。
我們來看以下代碼:

1 String name = Thread.currentThread().getName(); 2 int priority = Thread.currentThread().getPriority(); 3 String groupName = Thread.currentThread().getThreadGroup().getName(); 4 boolean isDaemon = Thread.currentThread().isDaemon(); 5 System.out.println("Thread Name:" + name); 6 System.out.println("Priority:" + priority); 7 System.out.println("Group Name:" + groupName); 8 System.out.println("IsDaemon:" + isDaemon); 9 10 Thread.currentThread().setName("Test"); 11 Thread.currentThread().setPriority(Thread.MAX_PRIORITY); 12 name = Thread.currentThread().getName(); 13 priority = Thread.currentThread().getPriority(); 14 groupName = Thread.currentThread().getThreadGroup().getName(); 15 isDaemon = Thread.currentThread().isDaemon(); 16 System.out.println("Thread Name:" + name); 17 System.out.println("Priority:" + priority);
其中列出的屬性說明如下:
- GroupName,每個線程都會默認在一個線程組里,我們也可以顯式的創建線程組,一個線程組中也可以包含子線程組,這樣線程和線程組,就構成了一個樹狀結構。
- Name,每個線程都會有一個名字,如果不顯式指定,那么名字的規則是“Thread-xxx”。
- Priority,每個線程都會有自己的優先級,JVM對優先級的處理方式是“搶占式”的。當JVM發現優先級高的線程時,馬上運行該線程;對於多個優先級相等的線程,JVM對其進行輪詢處理。Java的線程優先級從1到10,默認是5,Thread類定義了2個常量:MIN_PRIORITY和MAX_PRIORITY來表示最高和最低優先級。
我們可以看下面的代碼,它定義了兩個不同優先級的線程:
線程優先級示例
1 public static void priorityTest() 2 { 3 Thread thread1 = new Thread("low") 4 { 5 public void run() 6 { 7 for (int i = 0; i < 5; i++) 8 { 9 System.out.println("Thread 1 is running."); 10 } 11 } 12 }; 13 14 Thread thread2 = new Thread("high") 15 { 16 public void run() 17 { 18 for (int i = 0; i < 5; i++) 19 { 20 System.out.println("Thread 2 is running."); 21 } 22 } 23 }; 24 25 thread1.setPriority(Thread.MIN_PRIORITY); 26 thread2.setPriority(Thread.MAX_PRIORITY); 27 thread1.start(); 28 thread2.start(); 29 }
- isDaemon,這個屬性用來控制父子線程的關系,如果設置為true,當父線程結束后,其下所有子線程也結束,反之,子線程的生命周期不受父線程影響。
我們來看下面的例子:
IsDaemon 示例
1 public static void daemonTest() 2 { 3 Thread thread1 = new Thread("daemon") 4 { 5 public void run() 6 { 7 Thread subThread = new Thread("sub") 8 { 9 public void run() 10 { 11 for(int i = 0; i < 100; i++) 12 { 13 System.out.println("Sub Thread Running " + i); 14 } 15 } 16 }; 17 subThread.setDaemon(true); 18 subThread.start(); 19 System.out.println("Main Thread end."); 20 } 21 }; 22 23 thread1.start(); 24 }
上面代碼的運行結果,在和刪除subThread.setDaemon(true);后對比,可以發現后者運行過程中子線程會完成執行后再結束,而前者中,子線程很快就結束了。
如何創建線程
上面的內容,都是演示默認線程中的一些信息,那么應該如何創建線程呢?在Java中,我們有3種方式可以用來創建線程。
Java中的線程要么繼承Thread類,要么實現Runnable接口,我們一一道來。
使用內部類來創建線程
我們可以使用內部類的方式來創建線程,過程是聲明一個Thread類型的變量,並重寫run方法。示例代碼如下:

1 public static void createThreadByNestClass() 2 { 3 Thread thread = new Thread() 4 { 5 public void run() 6 { 7 for (int i =0; i < 5; i++) 8 { 9 System.out.println("Thread " + Thread.currentThread().getName() + " is running."); 10 } 11 System.out.println("Thread " + Thread.currentThread().getName() + " is finished."); 12 } 13 }; 14 thread.start(); 15 }
繼承Thread以創建線程
我們可以從Thread中派生一個類,重寫其run方法,這種方式和上面相似。示例代碼如下:

1 class MyThread extends Thread 2 { 3 public void run() 4 { 5 for (int i =0; i < 5; i++) 6 { 7 System.out.println("Thread " + Thread.currentThread().getName() + " is running."); 8 } 9 System.out.println("Thread " + Thread.currentThread().getName() + " is finished."); 10 } 11 } 12 13 14 public static void createThreadBySubClass() 15 { 16 MyThread thread = new MyThread(); 17 thread.start(); 18 }
實現Runnable接口以創建線程
我們可以定義一個類,使其實現Runnable接口,然后將該類的實例作為構建Thread變量構造函數的參數。示例代碼如下:

1 class MyRunnable implements Runnable 2 { 3 public void run() 4 { 5 for (int i =0; i < 5; i++) 6 { 7 System.out.println("Thread " + Thread.currentThread().getName() + " is running."); 8 } 9 System.out.println("Thread " + Thread.currentThread().getName() + " is finished."); 10 } 11 } 12 13 14 public static void createThreadByRunnable() 15 { 16 MyRunnable runnable = new MyRunnable(); 17 Thread thread = new Thread(runnable); 18 thread.start(); 19 }
上述3種方式都可以創建線程,而且從示例代碼上看,線程執行的功能是一樣的,那么這三種創建方式有什么不同呢?
這涉及到Java中多線程的運行模式,對於Java來說,多線程在運行時,有“多對象多線程”和“單對象多線程”的區別:
- 多對象多線程,程序在運行過程中創建多個線程對象,每個對象上運行一個線程。
- 單對象多線程,程序在運行過程中創建一個線程對象,在其上運行多個線程。
顯然,從線程同步和調度的角度來看,多對象多線程要簡單一些。上述3種線程創建方式,前兩種都屬於“多對象多線程”,第三種既可以使用“多對象多線程”,也可以使用“單對象單線程”。
我們來看下面的示例代碼,里面會用到Object.notify方法,這個方法會喚醒對象上的一個線程;而Object.notifyAll方法,則會喚醒對象上的所有線程。

1 public class NotifySample { 2 3 public static void main(String[] args) throws InterruptedException 4 { 5 notifyTest(); 6 notifyTest2(); 7 notifyTest3(); 8 } 9 10 private static void notifyTest() throws InterruptedException 11 { 12 MyThread[] arrThreads = new MyThread[3]; 13 for (int i = 0; i < arrThreads.length; i++) 14 { 15 arrThreads[i] = new MyThread(); 16 arrThreads[i].id = i; 17 arrThreads[i].setDaemon(true); 18 arrThreads[i].start(); 19 } 20 Thread.sleep(500); 21 for (int i = 0; i < arrThreads.length; i++) 22 { 23 synchronized(arrThreads[i]) 24 { 25 arrThreads[i].notify(); 26 } 27 } 28 } 29 30 private static void notifyTest2() throws InterruptedException 31 { 32 MyRunner[] arrMyRunners = new MyRunner[3]; 33 Thread[] arrThreads = new Thread[3]; 34 for (int i = 0; i < arrThreads.length; i++) 35 { 36 arrMyRunners[i] = new MyRunner(); 37 arrMyRunners[i].id = i; 38 arrThreads[i] = new Thread(arrMyRunners[i]); 39 arrThreads[i].setDaemon(true); 40 arrThreads[i].start(); 41 } 42 Thread.sleep(500); 43 for (int i = 0; i < arrMyRunners.length; i++) 44 { 45 synchronized(arrMyRunners[i]) 46 { 47 arrMyRunners[i].notify(); 48 } 49 } 50 } 51 52 private static void notifyTest3() throws InterruptedException 53 { 54 MyRunner runner = new MyRunner(); 55 Thread[] arrThreads = new Thread[3]; 56 for (int i = 0; i < arrThreads.length; i++) 57 { 58 arrThreads[i] = new Thread(runner); 59 arrThreads[i].setDaemon(true); 60 arrThreads[i].start(); 61 } 62 Thread.sleep(500); 63 64 synchronized(runner) 65 { 66 runner.notifyAll(); 67 } 68 } 69 } 70 71 class MyThread extends Thread 72 { 73 public int id = 0; 74 public void run() 75 { 76 System.out.println("第" + id + "個線程准備休眠5分鍾。"); 77 try 78 { 79 synchronized(this) 80 { 81 this.wait(5*60*1000); 82 } 83 } 84 catch(InterruptedException ex) 85 { 86 ex.printStackTrace(); 87 } 88 System.out.println("第" + id + "個線程被喚醒。"); 89 } 90 } 91 92 class MyRunner implements Runnable 93 { 94 public int id = 0; 95 public void run() 96 { 97 System.out.println("第" + id + "個線程准備休眠5分鍾。"); 98 try 99 { 100 synchronized(this) 101 { 102 this.wait(5*60*1000); 103 } 104 } 105 catch(InterruptedException ex) 106 { 107 ex.printStackTrace(); 108 } 109 System.out.println("第" + id + "個線程被喚醒。"); 110 } 111 112 }
示例代碼中,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對象上使用這兩個方法。
線程的休眠與喚醒

1 public class SleepSample { 2 3 public static void main(String[] args) throws InterruptedException 4 { 5 sleepTest(); 6 } 7 8 private static void sleepTest() throws InterruptedException 9 { 10 Thread thread = new Thread() 11 { 12 public void run() 13 { 14 System.out.println("線程 " + Thread.currentThread().getName() + "將要休眠5分鍾。"); 15 try 16 { 17 Thread.sleep(5*60*1000); 18 } 19 catch(InterruptedException ex) 20 { 21 System.out.println("線程 " + Thread.currentThread().getName() + "休眠被中斷。"); 22 } 23 System.out.println("線程 " + Thread.currentThread().getName() + "休眠結束。"); 24 } 25 }; 26 thread.setDaemon(true); 27 thread.start(); 28 Thread.sleep(500); 29 thread.interrupt(); 30 } 31 32 }
線程在休眠過程中,我們可以使用Thread.interrupt將其喚醒,這時線程會拋出InterruptedException。
線程的終止
雖然有Thread.stop方法,但該方法是不被推薦使用的,我們可以利用上面休眠與喚醒的機制,讓線程在處理IterruptedException時,結束線程。

1 public class StopThreadSample { 2 3 public static void main(String[] args) throws InterruptedException 4 { 5 stopTest(); 6 } 7 8 private static void stopTest() throws InterruptedException 9 { 10 Thread thread = new Thread() 11 { 12 public void run() 13 { 14 System.out.println("線程運行中。"); 15 try 16 { 17 Thread.sleep(1*60*1000); 18 } 19 catch(InterruptedException ex) 20 { 21 System.out.println("線程中斷,結束線程"); 22 return; 23 } 24 System.out.println("線程正常結束。"); 25 } 26 }; 27 thread.start(); 28 Thread.sleep(500); 29 thread.interrupt(); 30 } 31 }
線程的同步等待
當我們在主線程中創建了10個子線程,然后我們期望10個子線程全部結束后,主線程在執行接下來的邏輯,這時,就該Thread.join登場了。

1 public class JoinSample { 2 3 public static void main(String[] args) throws InterruptedException 4 { 5 joinTest(); 6 } 7 8 private static void joinTest() throws InterruptedException 9 { 10 Thread thread = new Thread() 11 { 12 public void run() 13 { 14 try 15 { 16 for(int i = 0; i < 5; i++) 17 { 18 System.out.println("線程在運行。"); 19 Thread.sleep(1000); 20 } 21 } 22 catch(InterruptedException ex) 23 { 24 ex.printStackTrace(); 25 } 26 } 27 }; 28 thread.setDaemon(true); 29 thread.start(); 30 Thread.sleep(1000); 31 thread.join(); 32 System.out.println("主線程正常結束。"); 33 } 34 }
我們可以試着將thread.join();注釋或者刪除,再次運行程序,就可以發現不同了。
線程間通信
我們知道,一個進程下面的所有線程是共享內存空間的,那么我們如何在不同的線程之間傳遞消息呢?在回顧 Java I/O時,我們談到了PipedStream和PipedReader,這里,就是它們發揮作用的地方了。
下面的兩個示例,功能完全一樣,不同的是一個使用Stream,一個使用Reader/Writer。

1 public static void communicationTest() throws IOException, InterruptedException 2 { 3 final PipedOutputStream pos = new PipedOutputStream(); 4 final PipedInputStream pis = new PipedInputStream(pos); 5 6 Thread thread1 = new Thread() 7 { 8 public void run() 9 { 10 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 11 try 12 { 13 while(true) 14 { 15 String message = br.readLine(); 16 pos.write(message.getBytes()); 17 if (message.equals("end")) break; 18 } 19 br.close(); 20 pos.close(); 21 } 22 catch(Exception ex) 23 { 24 ex.printStackTrace(); 25 } 26 } 27 }; 28 29 Thread thread2 = new Thread() 30 { 31 public void run() 32 { 33 byte[] buffer = new byte[1024]; 34 int bytesRead = 0; 35 try 36 { 37 while((bytesRead = pis.read(buffer, 0, buffer.length)) != -1) 38 { 39 System.out.println(new String(buffer)); 40 if (new String(buffer).equals("end")) break; 41 buffer = null; 42 buffer = new byte[1024]; 43 } 44 pis.close(); 45 buffer = null; 46 } 47 catch(Exception ex) 48 { 49 ex.printStackTrace(); 50 } 51 } 52 }; 53 54 thread1.setDaemon(true); 55 thread2.setDaemon(true); 56 thread1.start(); 57 thread2.start(); 58 thread1.join(); 59 thread2.join(); 60 }

1 private static void communicationTest2() throws InterruptedException, IOException 2 { 3 final PipedWriter pw = new PipedWriter(); 4 final PipedReader pr = new PipedReader(pw); 5 final BufferedWriter bw = new BufferedWriter(pw); 6 final BufferedReader br = new BufferedReader(pr); 7 8 Thread thread1 = new Thread() 9 { 10 public void run() 11 { 12 13 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 14 try 15 { 16 while(true) 17 { 18 String message = br.readLine(); 19 bw.write(message); 20 bw.newLine(); 21 bw.flush(); 22 if (message.equals("end")) break; 23 } 24 br.close(); 25 pw.close(); 26 bw.close(); 27 } 28 catch(Exception ex) 29 { 30 ex.printStackTrace(); 31 } 32 } 33 }; 34 35 Thread thread2 = new Thread() 36 { 37 public void run() 38 { 39 40 String line = null; 41 try 42 { 43 while((line = br.readLine()) != null) 44 { 45 System.out.println(line); 46 if (line.equals("end")) break; 47 } 48 br.close(); 49 pr.close(); 50 } 51 catch(Exception ex) 52 { 53 ex.printStackTrace(); 54 } 55 } 56 }; 57 58 thread1.setDaemon(true); 59 thread2.setDaemon(true); 60 thread1.start(); 61 thread2.start(); 62 thread1.join(); 63 thread2.join(); 64 }
這篇文章就到這里,我們會在下一篇里,討論同步的話題。