王之泰201771010131《面向物件程式設計(java)》第十七週學習總結
第一部分:理論知識學習部分
第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頁程式
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 }
第三部分:總結
在本週的學習中,我學習了執行緒同步這一知識點,我瞭解到這一知識點是用來解決多執行緒併發執行不確定性問題。並且這周是最後一週學習,助教學長為我們做了完整的演示來結束這學期的學習,總之,這學期在老師和助教學長的幫助下我們的學習能力有了很大的提升。感謝老師,也感謝助教學長!