java 多線程總結

線程一般有6個狀態:

新建狀態:NEW

可運行狀態:RUNNABLE

休眠狀態:TIMED_WAITING

等待狀態:WAITING

阻塞狀態:BLOCKED

終止狀態“TERMINATED

當我們使用new創建線程之後,線程處於新建狀態,當調用start方法之後,線程出於可運行狀態,當線程需要獲得對象的內置鎖,而這個鎖被其他線程所佔用的時候,線程就出於阻塞狀態,當線程等待其他線程通知調度表可以運行時,線程處於等待狀態,當一個含有時間參數的方法,必須sleep()方法,可以讓線程處於計時等待狀態,當run()方法運行完畢或者出現異常,線程處於終止狀態。

  1. package Thread;  
  2.    
  3. public class ThreadStateDemo{  
  4.     public static void main(String[] args) throws Exception{  
  5.         ThreadState state = new ThreadState();  
  6.         Thread demo = new Thread(state);  
  7.         System.out.println("新建狀態:" + demo.getState());  
  8.         demo.start();  
  9.         System.out.println("可運行狀態:" + demo.getState());  
  10.         Thread.sleep(100);  
  11.         System.out.println("休眠狀態:" + demo.getState());  
  12.         Thread.sleep(1000);  
  13.         System.out.println("等待狀態:" + demo.getState());  
  14.         state.notifyWait();  
  15.         System.out.println("阻塞狀態:" + demo.getState());  
  16.         Thread.sleep(1000);  
  17.         System.out.println("終止狀態“" + demo.getState());  
  18.     }  
  19. }  
  20.    
  21. class ThreadState implements Runnable{  
  22.    
  23.     @Override  
  24.     public void run(){  
  25.         try{  
  26.             waitForASecond();  
  27.             waitForAYear();  
  28.         }catch(Exception e){  
  29.             e.printStackTrace();  
  30.         }  
  31.    
  32.     }  
  33.    
  34.     // 當前線程等待1秒  
  35.     public synchronized void waitForASecond() throws Exception{  
  36.         wait(1000);  
  37.     }  
  38.    
  39.     // 當前線程一直等待  
  40.     public synchronized void waitForAYear() throws Exception{  
  41.         wait();  
  42.     }  
  43.    
  44.     // 喚醒線程  
  45.     public synchronized void notifyWait() throws Exception{  
  46.         notify();  
  47.     }  
  48. }  
【運行結果】:

新建狀態:NEW

可運行狀態:RUNNABLE

休眠狀態:TIMED_WAITING

等待狀態:WAITING

阻塞狀態:BLOCKED

終止狀態“TERMINATED

 

線程組表示一個線程線程的集合,線程組中也可以包含其他的線程組。線程組構成一棵樹。

  1. package Thread;  
  2.    
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.    
  6. public class ThreadGroupDemo{  
  7.     public static void main(String[] args){  
  8.         for(String str : getThreadGroups(GetRootThreadGroups())){  
  9.             System.out.println(str);  
  10.         }  
  11.     }  
  12.    
  13.     // 獲得根線程組  
  14.     private static ThreadGroup GetRootThreadGroups(){  
  15.         // 獲得當前的線程組  
  16.         ThreadGroup rootGroup = Thread.currentThread().getThreadGroup();  
  17.         while(true){  
  18.             if(rootGroup.getParent() != null){  
  19.                 rootGroup = rootGroup.getParent();  
  20.             }else{  
  21.                 break;  
  22.             }  
  23.         }  
  24.         return rootGroup;  
  25.     }  
  26.    
  27.     // 獲得給定線程組中所有線程名  
  28.     public static List<String> getThreads(ThreadGroup group){  
  29.         List<String> threadList = new ArrayList<String>();  
  30.         Thread[] threads = new Thread[group.activeCount()];  
  31.         int count = group.enumerate(threads, false);  
  32.         for(int i = 0; i < count; i++){  
  33.             threadList.add(group.getName() + " 線程組 " + threads[i].getName());  
  34.         }  
  35.         return threadList;  
  36.     }  
  37.    
  38.     // 獲得線程組中所有子線程組  
  39.     public static List<String> getThreadGroups(ThreadGroup group){  
  40.         List<String> threadList = getThreads(group);  
  41.         ThreadGroup[] groups = new ThreadGroup[group.activeGroupCount()];  
  42.         int count = group.enumerate(groups, false);  
  43.         for(int i = 0; i < count; i++){  
  44.             threadList.addAll(getThreads(groups[i]));  
  45.         }  
  46.         return threadList;  
  47.     }  
  48.    
  49. }  
【運行結果】:

system 線程組 Reference Handler

system 線程組 Finalizer

system 線程組 Signal Dispatcher

system 線程組 Attach Listener

main 線程組 main

 

使用守護線程

java中的線程分爲2類,用戶線程和守護線程,守護線程主要爲其他線程提供服務,守護線程會隨時被中斷,所以一般不要再守護線程中使用需要釋放資源的資源,比如輸入輸出流等,守護線程一般都是後臺線程,如果虛擬機只剩下守護線程,虛擬機就會退出。

  1. package Thread;  
  2.    
  3. public class DaemonThreadTest{  
  4.     public static void main(String[] args){  
  5.         Thread worker = new Thread(new Worker());  
  6.         Thread timer = new Thread(new Timer());  
  7.         //設置守護線程  
  8.         timer.setDaemon(true);  
  9.         worker.start();  
  10.         timer.start();  
  11.     }  
  12. }  
  13.    
  14. class Worker implements Runnable{  
  15.     @Override  
  16.     public void run(){  
  17.         for(int i = 0; i < 5; ++i){  
  18.             System.out.println("rollen真帥! 第" + i + "次");  
  19.         }  
  20.     }  
  21. }  
  22.    
  23. class Timer implements Runnable{  
  24.     @Override  
  25.     public void run(){  
  26.         long currentTime = System.currentTimeMillis();  
  27.         long processTime = 0;  
  28.         while(true){  
  29.             if((System.currentTimeMillis() - currentTime) > processTime){  
  30.                 processTime = System.currentTimeMillis() - currentTime;  
  31.                 System.out.println("程序運行時間:" + processTime);  
  32.             }  
  33.         }  
  34.     }  
  35. }  

rollen真帥0

程序運行時間:1

程序運行時間:2

程序運行時間:3

程序運行時間:4

程序運行時間:5

rollen真帥1

rollen真帥2

rollen真帥3

rollen真帥4

程序運行時間:6

終止指定的線程

雖然在Thread類中提供了stop()方法可以終止線程,但是由於其固有的不安全性,所以一般不要採用,本例子只是起到拋磚引玉的作用。

  1. package Thread;  
  2.    
  3. import java.awt.FlowLayout;  
  4. import java.awt.event.ActionEvent;  
  5. import java.awt.event.ActionListener;  
  6.    
  7. import javax.swing.JButton;  
  8. import javax.swing.JFrame;  
  9. import javax.swing.JLabel;  
  10. import javax.swing.JPanel;  
  11.    
  12. public class ThreadStopDemo extends JFrame{  
  13.     public ThreadStopDemo(){  
  14.         panel.setLayout(new FlowLayout(FlowLayout.CENTER));  
  15.         panel.add(label);  
  16.         panel.add(startButton);  
  17.         panel.add(endButton);  
  18.         setContentPane(panel);  
  19.         setSize(200300);  
  20.         setVisible(true);  
  21.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  22.    
  23.         startButton.addActionListener(new ActionListener(){  
  24.             @Override  
  25.             public void actionPerformed(ActionEvent e){  
  26.                 counter = new CounterThread();  
  27.                 new Thread(counter).start();  
  28.             }  
  29.         });  
  30.         endButton.addActionListener(new ActionListener(){  
  31.             @Override  
  32.             public void actionPerformed(ActionEvent e){  
  33.                 if(counter == null){  
  34.                     return;  
  35.                 }  
  36.                 counter.setStop(false);  
  37.             }  
  38.         });  
  39.     }  
  40.    
  41.     public static void main(String[] args){  
  42.         new ThreadStopDemo();  
  43.     }  
  44.    
  45.     class CounterThread implements Runnable{  
  46.         @Override  
  47.         public void run(){  
  48.             while(this.flag){  
  49.                 try{  
  50.                     Thread.sleep(500);  
  51.                 }catch(Exception e){  
  52.                     e.printStackTrace();  
  53.                 }  
  54.                 label.setText("更新" + (count++) + "更新");  
  55.             }  
  56.         }  
  57.    
  58.         public void setStop(boolean flag){  
  59.             this.flag = flag;  
  60.         }  
  61.    
  62.         private int count = 0;  
  63.         private boolean flag = true;  
  64.     }  
  65.    
  66.     private CounterThread counter = null;  
  67.     private final JPanel panel = new JPanel();  
  68.     private final JLabel label = new JLabel("更新0次");  
  69.     private final JButton startButton = new JButton("開始");  
  70.     private final JButton endButton = new JButton("結束");  
  71. }  
【運行結果】:


 

線程的插隊

在編寫多線程的程序的時候,經常會遇到讓一個線程優先於另外i個線程運行的情況,此時,除了設置這個線程的優先級高(不推薦這種方法)之外,更加直接的辦法是採用Thread類中的join()方法。當插隊的線程運行結束之後,其他的線程才能運行。

  1. package Thread;  
  2.    
  3. public class ThreadJoinDemo{  
  4.     public static void main(String[] args){  
  5.         Thread demo1 = new Thread(new EmergencyThread());  
  6.         demo1.start();  
  7.         for(int i = 0; i < 5; ++i){  
  8.             try{  
  9.                 Thread.sleep(100);  
  10.             }catch(InterruptedException e){  
  11.                 e.printStackTrace();  
  12.             }  
  13.             System.out.println("正常情況 :" + i + "號車開始出發");  
  14.             try{  
  15.                 //開始插隊  
  16.                 demo1.join();  
  17.             }catch(InterruptedException e){  
  18.                 e.printStackTrace();  
  19.             }  
  20.         }  
  21.     }  
  22. }  
  23.    
  24. class EmergencyThread implements Runnable{  
  25.     @Override  
  26.     public void run(){  
  27.         for(int i = 0; i < 5; ++i){  
  28.             try{  
  29.                 Thread.sleep(100);  
  30.             }catch(InterruptedException e){  
  31.                 e.printStackTrace();  
  32.             }  
  33.             System.out.println("緊急情況 :" + i + "號車開始出發");  
  34.         }  
  35.     }  
  36. }  
【運行結果】:

正常情況 :0號車開始出發

緊急情況0號車開始出發

緊急情況1號車開始出發

緊急情況2號車開始出發

緊急情況3號車開始出發

緊急情況4號車開始出發

正常情況 :1號車開始出發

正常情況 :2號車開始出發

正常情況 :3號車開始出發

正常情況 :4號車開始出發

如果我們去掉join哪一行的話,運行結果:(結果不唯一)

緊急情況0號車開始出發

正常情況 :0號車開始出發

緊急情況1號車開始出發

正常情況 :1號車開始出發

正常情況 :2號車開始出發

緊急情況2號車開始出發

緊急情況3號車開始出發

正常情況 :3號車開始出發

正常情況 :4號車開始出發

緊急情況4號車開始出發

線程的同步

多線程編程的一個重要原因是實現數據的共享,但是如果兩個線程同時修改一個數據的話,則會產生同步問題。

下面採用一個2個人同時往銀行存錢的例子,銀行卡初始金額爲100元。每次存10元,大家仔細查看餘額。(對於簡單的多線程,出錯的概率很小,今天很不巧,我一向地下的RP今天居然爆發了,實驗了很多次,都沒錯,最後終於出現了)

先看一下結果吧:


案例說兩側不能出現一樣餘額的。

代碼如下:

  1. package Thread;  
  2.    
  3. import java.awt.GridLayout;  
  4. import java.awt.event.ActionEvent;  
  5. import java.awt.event.ActionListener;  
  6.    
  7. import javax.swing.JButton;  
  8. import javax.swing.JFrame;  
  9. import javax.swing.JLabel;  
  10. import javax.swing.JPanel;  
  11. import javax.swing.JScrollPane;  
  12. import javax.swing.JTextArea;  
  13.    
  14. public class UnSynBank extends JFrame{  
  15.     public UnSynBank(){  
  16.         panel.setLayout(new GridLayout(2233));  
  17.         panel.add(label1);  
  18.         panel.add(label2);  
  19.         JScrollPane js1 = new JScrollPane(oneArea,  
  20.                 JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,  
  21.                 JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);  
  22.         panel.add(js1);  
  23.         JScrollPane js2 = new JScrollPane(twoArea,  
  24.                 JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,  
  25.                 JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);  
  26.         panel.add(js2);  
  27.    
  28.         panel2.add(panel);  
  29.         panel2.add(statrButton);  
  30.         setContentPane(panel2);  
  31.    
  32.         statrButton.addActionListener(new ActionListener(){  
  33.             @Override  
  34.             public void actionPerformed(ActionEvent e){  
  35.                 Thread demo1 = new Thread(new Transfer(bank, oneArea));  
  36.                 demo1.start();  
  37.                 Thread demo2 = new Thread(new Transfer(bank, twoArea));  
  38.                 demo2.start();  
  39.             }  
  40.         });  
  41.    
  42.         setSize(300400);  
  43.         setVisible(true);  
  44.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  45.     }  
  46.    
  47.     public static void main(String[] args){  
  48.         new UnSynBank();  
  49.     }  
  50.    
  51.     private final Bank bank = new Bank();  
  52.     JPanel panel = new JPanel();  
  53.     JPanel panel2 = new JPanel();  
  54.     private final JButton statrButton = new JButton("開始存錢");  
  55.     private final JLabel label1 = new JLabel("一號線程");  
  56.     private final JLabel label2 = new JLabel("二號線程");  
  57.     private final JTextArea oneArea = new JTextArea(510);  
  58.     private final JTextArea twoArea = new JTextArea(510);  
  59. }  
  60.    
  61. /** 
  62.  * 表示銀行的類 
  63.  * */  
  64. class Bank{  
  65.     public Bank(){  
  66.    
  67.     }  
  68.    
  69.     public void deposit(int money){  
  70.         account += money;  
  71.     }  
  72.    
  73.     public int getAccount(){  
  74.         return account;  
  75.     }  
  76.    
  77.     private int account = 100;  
  78. }  
  79.    
  80. /** 
  81.  * 表示往賬戶存錢 
  82.  * */  
  83. class Transfer implements Runnable{  
  84.     public Transfer(){  
  85.    
  86.     }  
  87.    
  88.     public Transfer(Bank bank, JTextArea textArea){  
  89.         this.bank = bank;  
  90.         this.textArea = textArea;  
  91.     }  
  92.    
  93.     @Override  
  94.     public void run(){  
  95.         for(int i = 0; i < 20; ++i){  
  96.             bank.deposit(10);  
  97.             String str = textArea.getText();  
  98.             textArea.setText(str + "賬戶餘額爲:" + bank.getAccount() + "\n");  
  99.         }  
  100.     }  
  101.    
  102.     private Bank bank = null;  
  103.     private JTextArea textArea = null;  
  104. }  

因爲一個進程中的所有線程會共享進程中的資源,所以當一個線程還沒有將修改之後的結果保存的時候,另外一個線程卻進行讀取,這樣自然會產生錯誤,所以這個時候就需要我們採用同步來解決問題的。

使用同步方法實現同步

所謂同步方法,就是用synchronized修飾的方法,之所以這十幾個字母能解決困難的同步問題,這是和java中的內置鎖密切相關的,每一個java對象中有一個內置鎖,如果方法使用了synchronized進行修飾的話,內置鎖會保護整個方法,也就是在調用方法之前,需要、獲得內置鎖,否則就會處於阻塞狀態,當然這個關鍵字也可以修飾靜態方法,如果調用靜態方法,就會鎖住整個類

 

現在我們來看看例子,我們顯著需要修改Bank類中的deposit方法,修改爲:

  1. public synchronized void deposit(int money){  
  2.         account += money;  
  3.     }  

然後無論你的RP再好,在怎麼運行,也不會出現兩個文本域中出現一樣的問題、另外讀者可以思考一樣,爲什麼需要鎖住這個方法呢?其實:account += money;的執行是分3步運行的,先讀取account的值,然後計算accountmoney的和,最後在存入account中,在多線程中,有可能兩個線程同時讀取account的值,這樣就會少計算一次money的值。

至於修改之後的運行結果,我就不粘貼了。

但是要提醒一下大家,同步是一種高開銷的操作,所以應該儘量減少需要同步的內容

使用特殊域變量實現同步

上面的例子中採用synchronized這個關鍵字同步了那個方法,其實我們會發現,就本例子中,之所以出現同步問題的原因在於對於域account的讀取上,那麼我們就可以將account設置爲特殊域變量。使用關鍵字volatile

volatile提供了一種免鎖的機制,使用這個關鍵字修飾的域相當於告訴虛擬機,這個域可能會被其他的線程跟新,因此每次讀取這個域的時候都需要重新計算,而不是使用寄存器中的值,這個關鍵字不會提供任何的原子操作,也不能用來修飾final類型的變量、

現在我們修改Bank方法:

privatevolatileintaccount = 100;

我們只需要加一個關鍵字就行了。

 

提醒一下:關於安全域的併發訪問:

多線程中的非同步問題出現在對於域的讀寫上的時候,如果讓域自身避免這個問題的話,則不需要修改操作的方法,在java中有3中域自身就可以避免非同步問題:final域,使用volatile域,以及有鎖保護的域。

使用重入鎖實現線程同步

  1. import java.util.concurrent.locks.Lock;  
  2. import java.util.concurrent.locks.ReentrantLock;  
可以在程序中添加上面兩行代碼,。然後將Bank修改爲:
  1. class Bank{  
  2.     public Bank(){  
  3.    
  4.     }  
  5.     public void deposit(int money){  
  6.         lock.lock();  
  7.         try{  
  8.             account += money;  
  9.         }finally{  
  10.             lock.unlock();  
  11.         }  
  12.     }  
  13.     public int getAccount(){  
  14.         return account;  
  15.     }  
  16.     private final Lock lock = new ReentrantLock();  
  17.     private int account = 100;  
  18. }  
這樣也可以解決非同步問題。至於這個類,大家可以自行去查看API,我只是在這裏提醒一下,如果synchronized能夠滿足需求的話,就使用synchronized關鍵字,因爲這個可以簡化代碼,如果需要更加高級的功能的時候,就使用Lock對象,在使用ReentrantLock的時候,一定要注意及時釋放鎖,否則程序會出現死鎖。

使用線程局部變量實現線程同步

這個例子演示的是兩個線程同時修改一個變量,運行結果:


可以發現,每個線程完成修改之後的副本是完全獨立的,如果使用TreadLocal來管理變量,則每個使用這個變量的線程都會獲得這個變量的一個副本。,並且可以隨意修改這個副本,每個線程之間不會影響。

TreadLocal和同步機制都是爲了解決多線程中的相同變量訪問衝突的問題的,前者採用的是空間還時間,後者採用的是時間換空間

代碼如下:

  1. class Bank{  
  2.     public Bank(){  
  3.    
  4.     }  
  5.     public void deposit(int money){  
  6.         account.set(account.get() + money);  
  7.     }  
  8.     public int getAccount(){  
  9.         return account.get();  
  10.     }  
  11.     private static ThreadLocal<Integer> account = new ThreadLocal<Integer>(){  
  12.         @Override  
  13.         protected Integer initialValue(){  
  14.             return 100;  
  15.         }  
  16.     };  
  17. }  
線程之間的通信

還記得我在我的筆記java IO總結中給出了一個使用管道流進行線程之間通信的例子:

  1. package Thread;  
  2.    
  3. import java.io.IOException;  
  4. import java.io.PipedInputStream;  
  5. import java.io.PipedOutputStream;  
  6.    
  7. /** 
  8.  * 使用管道流進行線程之間的通信 
  9.  * */  
  10. public class PipedTreadDemo{  
  11.     public static void main(String[] args){  
  12.         Sender send = new Sender();  
  13.         Reciver rec = new Reciver();  
  14.         try{  
  15.             send.getOut().connect(rec.getReciver());  
  16.         }catch(Exception e){  
  17.             e.printStackTrace();  
  18.         }  
  19.         new Thread(send).start();  
  20.         new Thread(rec).start();  
  21.     }  
  22. }  
  23.    
  24. /** 
  25.  * 消息發送類 
  26.  * */  
  27. class Sender implements Runnable{  
  28.     private PipedOutputStream out = null;  
  29.    
  30.     public Sender(){  
  31.         out = new PipedOutputStream();  
  32.     }  
  33.    
  34.     public PipedOutputStream getOut(){  
  35.         return this.out;  
  36.     }  
  37.    
  38.     @Override  
  39.     public void run(){  
  40.         String str = "rollen holt";  
  41.         try{  
  42.             out.write(str.getBytes());  
  43.         }catch(IOException e){  
  44.             e.printStackTrace();  
  45.         }  
  46.         try{  
  47.             out.close();  
  48.         }catch(IOException e){  
  49.             e.printStackTrace();  
  50.         }  
  51.     }  
  52. }  
  53.    
  54. /** 
  55.  * 消息接受類 
  56.  * */  
  57. class Reciver implements Runnable{  
  58.     private PipedInputStream input = null;  
  59.    
  60.     public Reciver(){  
  61.         input = new PipedInputStream();  
  62.     }  
  63.    
  64.     public PipedInputStream getReciver(){  
  65.         return this.input;  
  66.     }  
  67.    
  68.     @Override  
  69.     public void run(){  
  70.         byte[] bytes = new byte[1024];  
  71.         int len = 0;  
  72.         try{  
  73.             len = input.read(bytes);  
  74.         }catch(IOException e){  
  75.             e.printStackTrace();  
  76.         }  
  77.         try{  
  78.             input.close();  
  79.         }catch(IOException e){  
  80.             e.printStackTrace();  
  81.         }  
  82.         System.out.println("讀取的內容爲:" + new String(bytes, 0, len));  
  83.     }  
  84. }  

【運行結果】:

讀取的內容爲:rollenholt

下面,我們在同步的前提下,在舉出一個線程通信的例子:

首先擺出運行結果再說:


程序代碼如下:

  1. package Thread;  
  2.    
  3. /** 
  4.  * 線程之間的通信 
  5.  * */  
  6. import java.awt.GridLayout;  
  7. import java.awt.event.ActionEvent;  
  8. import java.awt.event.ActionListener;  
  9.    
  10. import javax.swing.JButton;  
  11. import javax.swing.JFrame;  
  12. import javax.swing.JLabel;  
  13. import javax.swing.JPanel;  
  14. import javax.swing.JScrollPane;  
  15. import javax.swing.JTextArea;  
  16.    
  17. public class TreadCommunicate extends JFrame{  
  18.     public TreadCommunicate(){  
  19.         panel.setLayout(new GridLayout(2233));  
  20.         panel.add(label1);  
  21.         panel.add(label2);  
  22.         JScrollPane js1 = new JScrollPane(oneArea,  
  23.                 JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,  
  24.                 JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);  
  25.         panel.add(js1);  
  26.         JScrollPane js2 = new JScrollPane(twoArea,  
  27.                 JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,  
  28.                 JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);  
  29.         panel.add(js2);  
  30.    
  31.         statrButton.addActionListener(new ActionListener(){  
  32.             @Override  
  33.             public void actionPerformed(ActionEvent e){  
  34.                 Sender sender = new Sender();  
  35.                 Thread demo1 = new Thread(sender);  
  36.                 Thread demo2 = new Thread(new Receiver(sender));  
  37.                 demo1.start();  
  38.                 demo2.start();  
  39.             }  
  40.         });  
  41.    
  42.         panel2.add(panel);  
  43.         panel2.add(statrButton);  
  44.         setContentPane(panel2);  
  45.    
  46.         setSize(300400);  
  47.         setVisible(true);  
  48.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  49.     }  
  50.    
  51.     public static void main(String[] args){  
  52.         new TreadCommunicate();  
  53.     }  
  54.    
  55.     /** 
  56.      * 賣家 
  57.      * */  
  58.     class Sender implements Runnable{  
  59.    
  60.         @Override  
  61.         public void run(){  
  62.             for(int i = 0; i < 5; ++i){  
  63.                 // 如果已經發送,那麼就等待  
  64.                 while(isValid){  
  65.                     Thread.yield();  
  66.                 }  
  67.                 product = products[i];  
  68.                 String text = oneArea.getText();  
  69.                 oneArea.setText(text + "發送" + product + "\n");  
  70.                 try{  
  71.                     Thread.sleep(1000);  
  72.                 }catch(Exception e){  
  73.                     e.printStackTrace();  
  74.                 }  
  75.                 isValid = true;  
  76.             }  
  77.         }  
  78.    
  79.         public boolean isisValid(){  
  80.             return this.isValid;  
  81.         }  
  82.    
  83.         public void setValid(boolean flag){  
  84.             this.isValid = flag;  
  85.         }  
  86.    
  87.         public String getProduct(){  
  88.             return product;  
  89.         }  
  90.    
  91.         private volatile String[] products = { "《***》""《紅樓夢》""《平凡的世界》",  
  92.                 "《流氓老師》""《西遊記》" };  
  93.         private volatile boolean isValid = false;  
  94.         private volatile String product;  
  95.     }// end sender  
  96.    
  97.     /** 
  98.      * 買家 
  99.      * */  
  100.     class Receiver implements Runnable{  
  101.         public Receiver(){  
  102.    
  103.         }  
  104.    
  105.         public Receiver(Sender sender){  
  106.             this.sender = sender;  
  107.         }  
  108.    
  109.         @Override  
  110.         public void run(){  
  111.             for(int i = 0; i < 5; ++i){  
  112.                 // 如果沒有發送,就等待  
  113.                 while(!sender.isisValid()){  
  114.                     Thread.yield();  
  115.                 }  
  116.                 String test = twoArea.getText();  
  117.                 twoArea.setText(test + "接受到" + sender.getProduct() + "\n");  
  118.                 try{  
  119.                     Thread.sleep(1000);  
  120.                 }catch(Exception e){  
  121.                     e.printStackTrace();  
  122.                 }  
  123.                 sender.setValid(false);  
  124.             }  
  125.         }  
  126.    
  127.         private Sender sender;  
  128.     }  
  129.    
  130.     JPanel panel = new JPanel();  
  131.     JPanel panel2 = new JPanel();  
  132.     private final JButton statrButton = new JButton("開始交易");  
  133.     private final JLabel label1 = new JLabel("賣家");  
  134.     private final JLabel label2 = new JLabel("買家");  
  135.     private final JTextArea oneArea = new JTextArea(510);  
  136.     private final JTextArea twoArea = new JTextArea(510);  
  137. }  

死鎖的範例

下面絕對不是本人蛋疼的寫出這個一個更加叫人蛋疼的程序。只是給出了一個例子:

  1. /** 
  2.  * 簡單的死鎖 
  3.  * */  
  4. public class DeadLockDemo implements Runnable{  
  5.     @Override  
  6.     public void run(){  
  7.         // 獲得當前線程的名字  
  8.         String str = Thread.currentThread().getName();  
  9.         System.out.println(str + ": flag= " + flag);  
  10.         if(flag){  
  11.             synchronized (obj1){  
  12.                 try{  
  13.                     Thread.sleep(1000);  
  14.                 }catch(Exception e){  
  15.                     e.printStackTrace();  
  16.                 }  
  17.                 System.out.println(str + "已經進入同步快obj1,準備進入同步快obj2");  
  18.                 synchronized (obj2){  
  19.                     System.out.println(str + "已經進入同步快obj2");  
  20.                 }  
  21.             }  
  22.         }  
  23.         if(!flag){  
  24.             synchronized (obj2){  
  25.                 try{  
  26.                     Thread.sleep(1000);  
  27.                 }catch(Exception e){  
  28.                     e.printStackTrace();  
  29.                 }  
  30.                 System.out.println(str + "已經進入同步快obj2,準備進入同步快obj1");  
  31.                 synchronized (obj1){  
  32.                     System.out.println(str + "已經進入同步快obj1");  
  33.                 }  
  34.             }  
  35.         }  
  36.     }  
  37.    
  38.     public static void main(String[] args){  
  39.         DeadLockDemo demo1 = new DeadLockDemo();  
  40.         DeadLockDemo demo2 = new DeadLockDemo();  
  41.         demo1.flag = true;  
  42.         demo2.flag = false;  
  43.         new Thread(demo1).start();  
  44.         new Thread(demo2).start();  
  45.     }  
  46.    
  47.     private boolean flag;  
  48.     private final Object obj1 = new Object();  
  49.     private final Object obj2 = new Object();  
  50. }  

【運行結果】

(我承認我今天RP爆發,我運行了10次,還是沒出現死鎖那種情況,但是這個程序確實可以產生死鎖的,哪位運行這個程序,要是產生了死鎖,麻煩說一下,謝謝)

 

使用線程池優化多線程編程

這個例子使用的是Executors類,讀者自行查看API,因爲要解說的話,就太多了。

下面這個例子給出了使用線程池和不使用線程池的情況下的效率的問題。

  1. package Thread;  
  2.    
  3. import java.util.concurrent.ExecutorService;  
  4. import java.util.concurrent.Executors;  
  5.    
  6. /** 
  7.  * 使用線程池優化多線程編程 
  8.  * */  
  9. public class ThreadPoolDemo{  
  10.     public static void main(String[] args){  
  11.         Runtime run = Runtime.getRuntime();  
  12.         // 爲了減少誤差  
  13.         run.gc();  
  14.         long currentTime = System.currentTimeMillis();  
  15.         long freemonery = run.freeMemory();  
  16.         for(int i = 0; i < 10000; ++i){  
  17.             new Thread(new Temo()).start();  
  18.         }  
  19.         System.out.println("獨立運行10000個線程佔用內存爲:"  
  20.                 + (freemonery - run.freeMemory()));  
  21.         System.out.println("獨立運行10000個線程佔用時間爲:"  
  22.                 + (System.currentTimeMillis() - currentTime));  
  23.         // 下面使用線程池來試試  
  24.         run.gc();  
  25.         freemonery = run.freeMemory();  
  26.         currentTime = System.currentTimeMillis();  
  27.         ExecutorService executorService = Executors.newFixedThreadPool(3);  
  28.         for(int i = 0; i < 10000; ++i){  
  29.             executorService.submit(new Temo());  
  30.         }  
  31.         System.out.println("使用線程池運行10000個線程佔用內存爲:"  
  32.                 + (freemonery - run.freeMemory()));  
  33.         System.out.println("使用線程池運行10000個線程佔用時間爲:"  
  34.                 + (System.currentTimeMillis() - currentTime));  
  35.     }  
  36. }  
  37.    
  38. class Temo implements Runnable{  
  39.     @Override  
  40.     public void run(){  
  41.         count++;  
  42.     }  
  43.    
  44.     private int count = 0;  
  45. }  

【運行結果】:

獨立運行10000個線程佔用內存爲:3490440

獨立運行10000個線程佔用時間爲:1808

使用線程池運行10000個線程佔用內存爲:1237424

使用線程池運行10000個線程佔用時間爲:62

使用信號量實現線程同步

現在我們繼續回答之前銀行存款的問題,相信大家還沒有忘記,哈哈,真是不好意思,本來線程同步這一塊應該整理在一起的。

一個信號量有3中操作,而且他們全部都是原子的,初始化,增加,減少。增加可以爲一個進程解除阻塞,減少可以爲一個進程進入阻塞。

Semaphore類是一個技術信號量,從概念上信號量維持了一個許可集。

現在我們繼續看上面的銀行存款問題:

  1. package Thread;  
  2.    
  3. import java.awt.GridLayout;  
  4. import java.awt.event.ActionEvent;  
  5. import java.awt.event.ActionListener;  
  6. import java.util.concurrent.Semaphore;  
  7.    
  8. import javax.swing.JButton;  
  9. import javax.swing.JFrame;  
  10. import javax.swing.JLabel;  
  11. import javax.swing.JPanel;  
  12. import javax.swing.JScrollPane;  
  13. import javax.swing.JTextArea;  
  14.    
  15. public class synDemo extends JFrame{  
  16.     public synDemo(){  
  17.         panel.setLayout(new GridLayout(2233));  
  18.         panel.add(label1);  
  19.         panel.add(label2);  
  20.         JScrollPane js1 = new JScrollPane(oneArea,  
  21.                 JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,  
  22.                 JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);  
  23.         panel.add(js1);  
  24.         JScrollPane js2 = new JScrollPane(twoArea,  
  25.                 JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,  
  26.                 JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);  
  27.         panel.add(js2);  
  28.    
  29.         panel2.add(panel);  
  30.         panel2.add(statrButton);  
  31.         setContentPane(panel2);  
  32.    
  33.         statrButton.addActionListener(new ActionListener(){  
  34.             @Override  
  35.             public void actionPerformed(ActionEvent e){  
  36.    
  37.                 Thread demo1 = new Thread(new Transfer1(bank, oneArea,  
  38.                         semaphore));  
  39.                 demo1.start();  
  40.                 Thread demo2 = new Thread(new Transfer1(bank, twoArea,  
  41.                         semaphore));  
  42.                 demo2.start();  
  43.             }  
  44.         });  
  45.    
  46.         setSize(300400);  
  47.         setVisible(true);  
  48.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  49.     }  
  50.    
  51.     public static void main(String[] args){  
  52.         new synDemo();  
  53.     }  
  54.    
  55.     Semaphore semaphore = new Semaphore(1true);  
  56.     private final Bank1 bank = new Bank1();  
  57.     JPanel panel = new JPanel();  
  58.     JPanel panel2 = new JPanel();  
  59.     private final JButton statrButton = new JButton("開始存錢");  
  60.     private final JLabel label1 = new JLabel("一號線程");  
  61.     private final JLabel label2 = new JLabel("二號線程");  
  62.     private final JTextArea oneArea = new JTextArea(510);  
  63.     private final JTextArea twoArea = new JTextArea(510);  
  64. }  
  65.    
  66. /** 
  67.  * 表示銀行的類 
  68.  * */  
  69. class Bank1{  
  70.     public Bank1(){  
  71.    
  72.     }  
  73.    
  74.     public void deposit(int money){  
  75.         account += money;  
  76.     }  
  77.    
  78.     public int getAccount(){  
  79.         return account;  
  80.     }  
  81.    
  82.     private int account;  
  83. }  
  84.    
  85. /** 
  86.  * 表示往賬戶存錢 
  87.  * */  
  88. class Transfer1 implements Runnable{  
  89.     public Transfer1(){  
  90.    
  91.     }  
  92.    
  93.     public Transfer1(Bank1 bank, JTextArea textArea, Semaphore semaphore){  
  94.         this.bank = bank;  
  95.         this.textArea = textArea;  
  96.         this.semaphore = semaphore;  
  97.     }  
  98.    
  99.     @Override  
  100.     public void run(){  
  101.         for(int i = 0; i < 20; ++i){  
  102.             // 獲得許可  
  103.             try{  
  104.                 semaphore.acquire();  
  105.             }catch(InterruptedException e){  
  106.                 e.printStackTrace();  
  107.             }  
  108.             bank.deposit(10);  
  109.             String str = textArea.getText();  
  110.             textArea.setText(str + "賬戶餘額爲:" + bank.getAccount() + "\n");  
  111.             // 釋放許可  
  112.             semaphore.release();  
  113.         }  
  114.     }  
  115.    
  116.     // 注意  
  117.     private Semaphore semaphore;  
  118.     private Bank1 bank = null;  
  119.     private JTextArea textArea = null;  
  120. }  

運行結果:


使用原子變量實現線程同步

  1. package Thread;  
  2.    
  3. import java.awt.GridLayout;  
  4. import java.awt.event.ActionEvent;  
  5. import java.awt.event.ActionListener;  
  6. import java.util.concurrent.atomic.AtomicInteger;  
  7.    
  8. import javax.swing.JButton;  
  9. import javax.swing.JFrame;  
  10. import javax.swing.JLabel;  
  11. import javax.swing.JPanel;  
  12. import javax.swing.JScrollPane;  
  13. import javax.swing.JTextArea;  
  14.    
  15. public class synDemo extends JFrame{  
  16.     public synDemo(){  
  17.         panel.setLayout(new GridLayout(2233));  
  18.         panel.add(label1);  
  19.         panel.add(label2);  
  20.         JScrollPane js1 = new JScrollPane(oneArea,  
  21.                 JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,  
  22.                 JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);  
  23.         panel.add(js1);  
  24.         JScrollPane js2 = new JScrollPane(twoArea,  
  25.                 JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,  
  26.                 JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);  
  27.         panel.add(js2);  
  28.    
  29.         panel2.add(panel);  
  30.         panel2.add(statrButton);  
  31.         setContentPane(panel2);  
  32.    
  33.         statrButton.addActionListener(new ActionListener(){  
  34.             @Override  
  35.             public void actionPerformed(ActionEvent e){  
  36.    
  37.                 Thread demo1 = new Thread(new Transfer1(bank, oneArea));  
  38.                 demo1.start();  
  39.                 Thread demo2 = new Thread(new Transfer1(bank, twoArea));  
  40.                 demo2.start();  
  41.             }  
  42.         });  
  43.    
  44.         setSize(300400);  
  45.         setVisible(true);  
  46.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  47.     }  
  48.    
  49.     public static void main(String[] args){  
  50.         new synDemo();  
  51.     }  
  52.    
  53.     private final Bank1 bank = new Bank1();  
  54.     JPanel panel = new JPanel();  
  55.     JPanel panel2 = new JPanel();  
  56.     private final JButton statrButton = new JButton("開始存錢");  
  57.     private final JLabel label1 = new JLabel("一號線程");  
  58.     private final JLabel label2 = new JLabel("二號線程");  
  59.     private final JTextArea oneArea = new JTextArea(510);  
  60.     private final JTextArea twoArea = new JTextArea(510);  
  61. }  
  62.    
  63. /** 
  64.  * 表示銀行的類 
  65.  * */  
  66. class Bank1{  
  67.     public Bank1(){  
  68.    
  69.     }  
  70.    
  71.     public void deposit(int money){  
  72.         account.addAndGet(money);  
  73.     }  
  74.    
  75.     public int getAccount(){  
  76.         return account.get();  
  77.     }  
  78.     //注意  
  79.     private final AtomicInteger account = new AtomicInteger(100);  
  80. }  
  81.    
  82. /** 
  83.  * 表示往賬戶存錢 
  84.  * */  
  85. class Transfer1 implements Runnable{  
  86.     public Transfer1(){  
  87.    
  88.     }  
  89.    
  90.     public Transfer1(Bank1 bank, JTextArea textArea){  
  91.         this.bank = bank;  
  92.         this.textArea = textArea;  
  93.     }  
  94.    
  95.     @Override  
  96.     public void run(){  
  97.         for(int i = 0; i < 20; ++i){  
  98.             bank.deposit(10);  
  99.             String str = textArea.getText();  
  100.             textArea.setText(str + "賬戶餘額爲:" + bank.getAccount() + "\n");  
  101.    
  102.         }  
  103.     }  
  104.    
  105.     private Bank1 bank = null;  
  106.     private JTextArea textArea = null;  
  107. }  
【運行結果】:


原文鏈接:http://www.cnblogs.com/rollenholt/archive/2011/09/15/2178030.html
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章