1. 程式人生 > >王之泰201771010131《面向對象程序設計(java)》第十七周學習總結

王之泰201771010131《面向對象程序設計(java)》第十七周學習總結

系統 方案 java se not 調試 編程練習 current except exceptio

第一部分:理論知識學習部分

第14章 並發

線程同步

多線程並發運行不確定性問題解決方案:引入線 程同步機制,使得另一線程要使用該方法,就只 能等待。

? 在Java中解決多線程同步問題的方法有兩種:

1.- Java SE 5.0中引入ReentrantLock類(P648頁)。

2.- 在共享內存的類方法前加synchronized修飾符。

……

public synchronized static void sub(int m)

……

解決方案一:鎖對象與條件對象

用ReentrantLock保護代碼塊的基本結構如下:

myLock.lock();

try {

   critical section

} finally{

myLock.unlock(); }

有關鎖對象和條件對象的關鍵要點:

? 鎖用來保護代碼片段,保證任何時刻只能有一 個線程執行被保護的代碼。

? 鎖管理試圖進入被保護代碼段的線程。

? 鎖可擁有一個或多個相關條件對象。

? 每個條件對象管理那些已經進入被保護的代碼 段但還不能運行的線程。

解決方案二: synchronized關鍵字

synchronized關鍵字作用:

? 某個類內方法用synchronized 修飾後,該方法被稱為同步方法;

? 只要某個線程正在訪問同步方法,其他線程欲要訪問同步方法就被阻塞,直至線程從同步方法返回前喚醒被阻塞線程,其他線程方可能進入同步方法。

? 一個線程在使用的同步方法中時,可能根據問題的需要,必須使用wait()方法使本線程等待,暫時讓出CPU的使用權,並允許其它線程使用這個同步方法。

? 線程如果用完同步方法,應當執行notifyAll()方 法通知所有由於使用這個同步方法而處於等待的 線程結束等待。

第二部分:實驗部分——線程同步控制

實驗時間 2018-12-10

1、實驗目的與要求

(1) 掌握線程同步的概念及實現技術;

(2) 線程綜合編程練習

2、實驗內容和步驟

實驗1:測試程序並進行代碼註釋。

測試程序1:

1.在Elipse環境下調試教材651頁程序14-7,結合程序運行結果理解程序;

2.掌握利用鎖對象和條件對象實現的多線程同步技術。

 1 package synch;
 2 
 3 import java.util.*;
 4 import java.util.concurrent.locks.*;
 5 
 6 /**
 7 一個銀行有許多銀行帳戶,使用鎖序列化訪問 * @version 1.30 2004-08-01
 8  * @author Cay Horstmann
 9  */
10 public class Bank
11 {
12    private final double[] accounts;
13    private Lock bankLock;
14    private Condition sufficientFunds;
15 
16    /**
17     * 建設銀行。
18     * @param n 賬號
19     * @param initialBalance 每個賬戶的初始余額
20     */
21    public Bank(int n, double initialBalance)
22    {
23       accounts = new double[n];
24       Arrays.fill(accounts, initialBalance);
25       bankLock = new ReentrantLock();
26       sufficientFunds = bankLock.newCondition();
27    }
28 
29    /**
30     * 把錢從一個賬戶轉到另一個賬戶。
31     * @param 從賬戶轉賬
32     * @param 轉到要轉賬的賬戶
33     * @param 請允許我向你轉達
34     */
35    public void transfer(int from, int to, double amount) throws InterruptedException
36    {
37       bankLock.lock();
38       try
39       {
40          while (accounts[from] < amount)
41             sufficientFunds.await();
42          System.out.print(Thread.currentThread());
43          accounts[from] -= amount;
44          System.out.printf(" %10.2f from %d to %d", amount, from, to);
45          accounts[to] += amount;
46          System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
47          sufficientFunds.signalAll();
48       }
49       finally
50       {
51          bankLock.unlock();
52       }
53    }
54 
55    /**
56     * 獲取所有帳戶余額的總和。
57     * @return 總余額
58     */
59    public double getTotalBalance()
60    {
61       bankLock.lock();
62       try
63       {
64          double sum = 0;
65 
66          for (double a : accounts)
67             sum += a;
68 
69          return sum;
70       }
71       finally
72       {
73          bankLock.unlock();
74       }
75    }
76 
77    /**
78     * 獲取銀行中的帳戶數量。
79     * @return 賬號
80     */
81    public int size()
82    {
83       return accounts.length;
84    }
85 }

 1 package synch;
 2 
 3 /**
 4  * 這個程序顯示了多個線程如何安全地訪問數據結構。
 5  * @version 1.31 2015-06-21
 6  * @author Cay Horstmann
 7  */
 8 public class SynchBankTest
 9 {
10    public static final int NACCOUNTS = 100;
11    public static final double INITIAL_BALANCE = 1000;
12    public static final double MAX_AMOUNT = 1000;
13    public static final int DELAY = 10;
14    
15    public static void main(String[] args)
16    {
17       Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE);
18       for (int i = 0; i < NACCOUNTS; i++)
19       {
20          int fromAccount = i;
21          Runnable r = () -> {
22             try
23             {
24                while (true)
25                {
26                   int toAccount = (int) (bank.size() * Math.random());
27                   double amount = MAX_AMOUNT * Math.random();
28                   bank.transfer(fromAccount, toAccount, amount);
29                   Thread.sleep((int) (DELAY * Math.random()));
30                }
31             }
32             catch (InterruptedException e)
33             {
34             }            
35          };
36          Thread t = new Thread(r);
37          t.start();
38       }
39    }
40 }

技術分享圖片

測試程序2:

1.在Elipse環境下調試教材655頁程序14-8,結合程序運行結果理解程序;

2.掌握synchronized在多線程同步中的應用。

 1 package synch2;
 2 
 3 import java.util.*;
 4 
 5 /**
 6  * 具有多個使用同步原語的銀行賬戶的銀行。
 7  * @version 1.30 2004-08-01
 8  * @author Cay Horstmann
 9  */
10 public class Bank
11 {
12    private final double[] accounts;
13 
14    /**
15     * 建設銀行。
16     * @param n 賬號
17     * @param initialBalance 每個賬戶的初始余額
18     */
19    public Bank(int n, double initialBalance)
20    {
21       accounts = new double[n];
22       Arrays.fill(accounts, initialBalance);
23    }
24 
25    /**
26     * 把錢從一個賬戶轉到另一個賬戶。
27     * @param 從賬戶轉賬
28     * @param 轉到要轉賬的賬戶
29     * @param 請允許我向你轉達
30     */
31    public synchronized void transfer(int from, int to, double amount) throws InterruptedException
32    {
33       while (accounts[from] < amount)
34          wait();
35       System.out.print(Thread.currentThread());
36       accounts[from] -= amount;
37       System.out.printf(" %10.2f from %d to %d", amount, from, to);
38       accounts[to] += amount;
39       System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
40       notifyAll();
41    }
42 
43    /**
44     * 獲取所有帳戶余額的總和。
45     * @return 總余額
46     */
47    public synchronized double getTotalBalance()
48    {
49       double sum = 0;
50 
51       for (double a : accounts)
52          sum += a;
53 
54       return sum;
55    }
56 
57    /**
58     * 獲取銀行中的帳戶數量。
59     * @return 
60     */
61    public int size()
62    {
63       return accounts.length;
64    }
65 }

 1 package synch2;
 2 
 3 /**
 4  * 
 5  * 這個程序展示了多個線程如何使用同步方法安全地訪問數據結構。
 6  * @version 1.31 2015-06-21
 7  * @author Cay Horstmann
 8  */
 9 public class SynchBankTest2
10 {
11    public static final int NACCOUNTS = 100;
12    public static final double INITIAL_BALANCE = 1000;
13    public static final double MAX_AMOUNT = 1000;
14    public static final int DELAY = 10;
15 
16    public static void main(String[] args)
17    {
18       Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE);
19       for (int i = 0; i < NACCOUNTS; i++)
20       {
21          int fromAccount = i;
22          Runnable r = () -> {
23             try
24             {
25                while (true)
26                {
27                   int toAccount = (int) (bank.size() * Math.random());
28                   double amount = MAX_AMOUNT * Math.random();
29                   bank.transfer(fromAccount, toAccount, amount);
30                   Thread.sleep((int) (DELAY * Math.random()));
31                }
32             }
33             catch (InterruptedException e)
34             {
35             }
36          };
37          Thread t = new Thread(r);
38          t.start();
39       }
40    }
41 }

測試程序3:

1.在Elipse環境下運行以下程序,結合程序運行結果分析程序存在問題;

2.嘗試解決程序中存在問題。

 1 package sdfsd;
 2 
 3 class Cbank
 4 {
 5      private static int s=2000;
 6      public   static void sub(int m)
 7      {
 8            int temp=s;
 9            temp=temp-m;
10           try {
11                  Thread.sleep((int)(1000*Math.random()));
12                }
13            catch (InterruptedException e)  {              }
14               s=temp;
15               System.out.println("s="+s);
16           }
17     }
18 
19 
20 class Customer extends Thread
21 {
22   public void run()
23   {
24    for( int i=1; i<=4; i++)
25      Cbank.sub(100);
26     }
27  }
28 public class Thread3
29 {
30  public static void main(String args[])
31   {
32    Customer customer1 = new Customer();
33   
34    Customer customer2 = new Customer();
35    customer1.start();
36    customer2.start();
37   }
38 }

技術分享圖片

改進

 1 package sdfsd;
 2 
 3 class Cbank
 4 {
 5      private static int s=2000;
 6      public  synchronized static void sub(int m)
 7      {
 8            int temp=s;
 9            temp=temp-m;
10           try {
11                  Thread.sleep((int)(1000*Math.random()));
12                }
13            catch (InterruptedException e)  {              }
14               s=temp;
15               System.out.println("s="+s);
16           }
17     }
18 
19 
20 class Customer extends Thread
21 {
22   public void run()
23   {
24    for( int i=1; i<=4; i++)
25      Cbank.sub(100);
26     }
27  }
28 
29 public class Thread3
30 {
31  public static void main(String args[])
32   {
33    Customer customer1 = new Customer();
34   
35    Customer customer2 = new Customer();
36    customer1.start();
37    customer2.start();
38   }
39 }

技術分享圖片

實驗2 編程練習

利用多線程及同步方法,編寫一個程序模擬火車票售票系統,共3個窗口,賣10張票,程序輸出結果類似(程序輸出不唯一,可以是其他類似結果)。

Thread-0窗口售:第1張票

Thread-0窗口售:第2張票

Thread-1窗口售:第3張票

Thread-2窗口售:第4張票

Thread-2窗口售:第5張票

Thread-1窗口售:第6張票

Thread-0窗口售:第7張票

Thread-2窗口售:第8張票

Thread-1窗口售:第9張票

Thread-0窗口售:第10張票

 1 public class Demo {
 2     public static void main(String[] args) {
 3         Mythread mythread = new Mythread();
 4         Thread ticket1 = new Thread(mythread);
 5         Thread ticket2 = new Thread(mythread);
 6         Thread ticket3 = new Thread(mythread);
 7         ticket1.start();
 8         ticket2.start();
 9         ticket3.start();
10     }
11 }
12 
13 class Mythread implements Runnable {
14     int ticket = 1;
15     boolean flag = true;
16 
17     @Override
18     public void run() {
19         while (flag) {
20             try {
21                 Thread.sleep(500);
22             } catch (InterruptedException e) {
23                 // TODO Auto-generated catch block
24                 e.printStackTrace();
25             }
26 
27             synchronized (this) {
28                 if (ticket <= 10) {
29                     System.out.println(Thread.currentThread().getName() + "窗口售:第" + ticket + "張票");
30                     ticket++;
31                 }
32                 if (ticket > 10) {
33                     flag = false;
34                 }
35             }
36         }
37     }
38 
39 }

技術分享圖片

第三部分:總結

  在本周的學習中,我學習了線程同步這一知識點,我了解到這一知識點是用來解決多線程並發運行不確定性問題。並且這周是最後一周學習,助教學長為我們做了完整的演示來結束這學期的學習,總之,這學期在老師和助教學長的幫助下我們的學習能力有了很大的提升。感謝老師,也感謝助教學長!

王之泰201771010131《面向對象程序設計(java)》第十七周學習總結