1. 程式人生 > >201771010113 李婷華 《面向物件程式設計(Java)》第十七週總結

201771010113 李婷華 《面向物件程式設計(Java)》第十七週總結

一.理論知識部分

 Java 的執行緒排程採用優先順序策略:優先順序高的先執行,優先順序低的後執行;多執行緒系統會自動為每個執行緒分配一個優先順序,預設時,繼承其父類的優先順序; 任務緊急的執行緒,其優先順序較高; 同優先順序的執行緒按“先進先出”的佇列原則。

呼叫setPriority(int a)重置當前執行緒的優先順序,a取值可以是前述的三個靜態量。呼叫getPriority()獲得當前執行緒優先順序。

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

在Java中解決多執行緒同步問題的方法有兩種:J ava SE 5.0中引入ReentrantLock類。 在共享記憶體的類方法前加synchronized修飾符。

有關鎖物件和條件物件的關鍵要點:鎖用來保護程式碼片段,保證任何時刻只能有一個執行緒執行被保護的程式碼。鎖管理試圖進入被保護程式碼段的執行緒。鎖可擁有一個或多個相關條件物件。每個條件物件管理那些已經進入被保護的程式碼 段但還不能執行的執行緒。

synchronized關鍵字作用: 某個類內方法用synchronized 修飾後,該方法被稱為同步方法;只要某個執行緒正在訪問同步方法,其他執行緒欲要訪問同步方法就被阻塞,直至執行緒從同 步方法返回前喚醒被阻塞執行緒,其他執行緒方可能進入同步方法。

在同步方法中使用wait()、notify 和notifyAll()方法:一個執行緒在使用的同步方法中時,可能根據問題的需要,必須使用wait()方法使本執行緒等待,暫時讓出CPU的使用權,並允許其它執行緒使用這個同步方法。執行緒如果用完同步方法,應當執行notifyAll()方 法通知所有由於使用這個同步方法而處於等待的執行緒結束等待。

二.實驗部分

1、實驗目的與要求

(1) 掌握執行緒同步的概念及實現技術; 

(2) 執行緒綜合程式設計練習

2、實驗內容和步驟

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

測試程式1:

l 在Elipse環境下除錯教材651頁程式14-7,結合程式執行結果理解程式;

l 掌握利用鎖物件和條件物件實現的多執行緒同步技術。

 1 package synch;
 2 
 3 /**
 4  * This program shows how multiple threads can safely access a data structure.
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 }
SynchBankTest
 1 package synch;
 2 
 3 import java.util.*;
 4 import java.util.concurrent.locks.*;
 5 
 6 /**
 7  * A bank with a number of bank accounts that uses locks for serializing access.
 8  * @version 1.30 2004-08-01
 9  * @author Cay Horstmann
10  */
11 public class Bank
12 {
13    private final double[] accounts;
14    private Lock bankLock;
15    private Condition sufficientFunds;
16 
17    /**
18     * Constructs the bank.
19     * @param n the number of accounts
20     * @param initialBalance the initial balance for each account
21     */
22    public Bank(int n, double initialBalance)
23    {
24       accounts = new double[n];
25       Arrays.fill(accounts, initialBalance);
26       bankLock = new ReentrantLock();
27       sufficientFunds = bankLock.newCondition();
28    }
29 
30    /**
31     * Transfers money from one account to another.
32     * @param from the account to transfer from
33     * @param to the account to transfer to
34     * @param amount the amount to transfer
35     */
36    public void transfer(int from, int to, double amount) throws InterruptedException
37    {
38       bankLock.lock();//使用鎖物件,獲取鎖
39       try
40       {
41          while (accounts[from] < amount)
42             sufficientFunds.await();
43          System.out.print(Thread.currentThread());
44          accounts[from] -= amount;
45          System.out.printf(" %10.2f from %d to %d", amount, from, to);
46          accounts[to] += amount;
47          System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
48          sufficientFunds.signalAll();//喚醒所有執行緒
49       }
50       finally
51       {
52          bankLock.unlock();//釋放鎖
53       }
54    }
55 
56    /**
57     * Gets the sum of all account balances.
58     * @return the total balance
59     */
60    public double getTotalBalance()
61    {
62       bankLock.lock();
63       try
64       {
65          double sum = 0;
66 
67          for (double a : accounts)
68             sum += a;
69 
70          return sum;
71       }
72       finally
73       {
74          bankLock.unlock();
75       }
76    }
77 
78    /**
79     * Gets the number of accounts in the bank.
80     * @return the number of accounts
81     */
82    public int size()
83    {
84       return accounts.length;
85    }
86 }
Bank

測試程式2:

l 在Elipse環境下除錯教材655頁程式14-8,結合程式執行結果理解程式;

l 掌握synchronized在多執行緒同步中的應用。

 1 package synch2;
 2 
 3 import java.util.*;
 4 
 5 /**
 6  * A bank with a number of bank accounts that uses synchronization primitives.
 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     * Constructs the bank.
16     * @param n the number of accounts
17     * @param initialBalance the initial balance for each account
18     */
19    public Bank(int n, double initialBalance)
20    {
21       accounts = new double[n];
22       Arrays.fill(accounts, initialBalance);
23    }
24 
25    /**
26     * Transfers money from one account to another.
27     * @param from the account to transfer from
28     * @param to the account to transfer to
29     * @param amount the amount to transfer
30     */
31    //使用synchronized修飾符
32    public synchronized void transfer(int from, int to, double amount) throws InterruptedException
33    {
34       while (accounts[from] < amount)
35          wait();//來自Object類
36       System.out.print(Thread.currentThread());
37       accounts[from] -= amount;
38       System.out.printf(" %10.2f from %d to %d", amount, from, to);
39       accounts[to] += amount;
40       System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
41       notifyAll();//解除所有執行緒的阻塞狀態
42    }
43 
44    /**
45     * Gets the sum of all account balances.
46     * @return the total balance
47     */
48    public synchronized double getTotalBalance()
49    {
50       double sum = 0;
51 
52       for (double a : accounts)
53          sum += a;
54 
55       return sum;
56    }
57 
58    /**
59     * Gets the number of accounts in the bank.
60     * @return the number of accounts
61     */
62    public int size()
63    {
64       return accounts.length;
65    }
66 }
Bank

 

 1 package synch2;
 2 
 3 /**
 4  * This program shows how multiple threads can safely access a data structure,
 5  * using synchronized methods.
 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 }
SynchBankTest2

測試程式3:

l 在Elipse環境下執行以下程式,結合程式執行結果分析程式存在問題;

l 嘗試解決程式中存在問題。

class Cbank

{

     private static int s=2000;

     public   static void sub(int m)

     {

           int temp=s;

           temp=temp-m;

          try {

      Thread.sleep((int)(1000*Math.random()));

    }

           catch (InterruptedException e)  {              }

           s=temp;

           System.out.println("s="+s);

   }

}

 

 

class Customer extends Thread

{

  public void run()

  {

   for( int i=1; i<=4; i++)

     Cbank.sub(100);

    }

 }

public class Thread3

{

 public static void main(String args[])

  {

   Customer customer1 = new Customer();

   Customer customer2 = new Customer();

   customer1.start();

   customer2.start();

  }

}

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

實驗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         Myrhread myrhread = new Myrhread();
 4         Thread t1 = new Thread(myrhread);
 5         Thread t2 = new Thread(myrhread);
 6         Thread t3 = new Thread(myrhread);
 7         t1.start();
 8         t2.start();
 9         t3.start();
10     }
11 }
12 
13 class Myrhread implements Runnable {
14     int t = 1;
15     boolean flag = true;
16 
17     public void run() {
18         while (flag) {
19             try {
20                 Thread.sleep(500);
21             } catch (InterruptedException e) {
22                 e.printStackTrace();
23             }
24             synchronized (this) {
25                 if (t <= 10) {
26                     System.out.println(Thread.currentThread().getName() + "視窗售:第" + t + "張票");
27                     t++;
28                 }
29                 if (t > 10) {
30                     flag = false;
31                 }
32             }
33         }
34 
35     }
36 }
Demo

3.實驗總結:

本週的實驗容量很少,實驗也相對來說簡單,完成的還算順利。學長也教了我們常用的一些快捷鍵,本週的收穫還是很大的。