201771010137 趙棟《面向對象程序設計(java)》第十七周學習總結
一、理論部分
1、多線程並發執行中的問題
i.多個線程相對執行的順序是不確定的。
ii.線程執行順序的不確定性會產生執行結果的不確定性。
iii.在多線程對共享數據操作時常常會產生這種不確定性。
2、線程的同步
-多線程並發運行不確定性問題解決方案:引入線程同步機制,使得另一線程要使用該方法,就只能等待。
- 在Java中解決多線程同步問題的方法有兩種:
- Java SE 5.0中引入ReentrantLock類
- 在共享內存的類方法前加synchronized修飾符。
……
public synchronized static void sub(int m)
……
(1)解決方案一:鎖對象與條件對象
用ReentrantLock保護代碼塊的基本結構如下:
myLock.lock();
try {
critical section
}
finally
{
myLock.unlock();
}
有關鎖對象和條件對象的關鍵要點:
? 鎖用來保護代碼片段,保證任何時刻只能有一個線程執行被保護的代碼。
? 鎖管理試圖進入被保護代碼段的線程。
? 鎖可擁有一個或多個相關條件對象。
? 每個條件對象管理那些已經進入被保護的代碼段但還不能運行的線程。
(2)解決方案二: synchronized關鍵字
synchronized關鍵字作用:
?某個類內方法用synchronized 修飾後,該方法被稱為同步方法;
?只要某個線程正在訪問同步方法,其他線程欲要訪問同步方法就被阻塞,直至線程從同步方法返回前喚醒被阻塞線程,其他線程方可能進入同步方法。
3、在同步方法中使用wait()、notify 和notifyAll()方法
? 一個線程在使用的同步方法中時,可能根據問題的需要,必須使用wait()方法使本線程等待,暫時讓出CPU的使用權,並允許其它線程使用這個同步方法。
? 線程如果用完同步方法,應當執行notifyAll()方法通知所有由於使用這個同步方法而處於等待的線程結束等待。
二、實驗部分
1、實驗目的與要求
(1) 掌握線程同步的概念及實現技術;
(2) 線程綜合編程練習
2、實驗內容和步驟
實驗1:測試程序並進行代碼註釋。
測試程序1:
l 在Elipse環境下調試教材651頁程序14-7,結合程序運行結果理解程序;
l 掌握利用鎖對象和條件對象實現的多線程同步技術
package synch; import java.util.*; import java.util.concurrent.locks.*; /** * 一種擁有許多銀行帳戶的銀行,它使用鎖來序列化訪問。 * @version 1.30 2004-08-01 * @author Cay Horstmann */ public class Bank { private final double[] accounts; private Lock bankLock; private Condition sufficientFunds; /** *構建了銀行。 * @param 賬戶數量 * @param 每個賬戶的初始余額 */ public Bank(int n, double initialBalance) { accounts = new double[n]; Arrays.fill(accounts, initialBalance); bankLock = new ReentrantLock(); sufficientFunds = bankLock.newCondition(); } /** * 把錢從一個賬戶轉到另一個賬戶。 * @param 從賬戶轉出 * @param 到賬轉到 * @param 轉帳金額 */ public void transfer(int from, int to, double amount) throws InterruptedException { bankLock.lock(); try { while (accounts[from] < amount) sufficientFunds.await();//註釋掉之後產生死鎖現象,都在等待 System.out.print(Thread.currentThread()); accounts[from] -= amount; System.out.printf(" %10.2f from %d to %d", amount, from, to); accounts[to] += amount; System.out.printf(" Total Balance: %10.2f%n", getTotalBalance()); sufficientFunds.signalAll();//註釋掉之後產生死鎖現象,都在等待 } finally { bankLock.unlock(); } } /** *獲取所有帳戶余額的總和。 * @return 總平衡 */ public double getTotalBalance()//為什麽只需要加鎖不需要設置對象?沒有任何執行不下去的原因,就不需要條件對象。 { bankLock.lock(); try { double sum = 0; for (double a : accounts) sum += a; return sum; } finally { bankLock.unlock(); } } /** * 獲取銀行中的帳戶編號。 * @return 賬戶數量 */ public int size() { return accounts.length; } }
package synch; /** * 這個程序展示了多線程如何安全地訪問數據結構。 * @version 1.31 2015-06-21 * @author Cay Horstmann */ public class SynchBankTest { public static final int NACCOUNTS = 100; public static final double INITIAL_BALANCE = 1000; public static final double MAX_AMOUNT = 1000; public static final int DELAY = 10; public static void main(String[] args) { Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE); for (int i = 0; i < NACCOUNTS; i++) { int fromAccount = i; Runnable r = () -> { try { while (true) { int toAccount = (int) (bank.size() * Math.random()); double amount = MAX_AMOUNT * Math.random(); bank.transfer(fromAccount, toAccount, amount); Thread.sleep((int) (DELAY * Math.random())); } } catch (InterruptedException e) { } }; Thread t = new Thread(r); t.start(); } } }
實驗結果如下圖所示:
測試程序2:
l 在Elipse環境下調試教材655頁程序14-8,結合程序運行結果理解程序;
l 掌握synchronized在多線程同步中的應用。
package synch2; import java.util.*; /** * 使用同步原語的具有多個銀行帳戶的銀行 * @version 1.30 2004-08-01 * @author Cay Horstmann */ public class Bank { private final double[] accounts; /** * 構建了銀行。 * @param 賬戶數量 * @param 每個賬戶的初始余額 */ public Bank(int n, double initialBalance) { accounts = new double[n]; Arrays.fill(accounts, initialBalance); } /** * 把錢從一個賬戶轉到另一個賬戶。 * @param 從賬戶轉出 * @param 到賬轉到 * @param 轉帳金額 */ public synchronized void transfer(int from, int to, double amount) throws InterruptedException { while (accounts[from] < amount) wait();//Object類 System.out.print(Thread.currentThread()); accounts[from] -= amount; System.out.printf(" %10.2f from %d to %d", amount, from, to); accounts[to] += amount; System.out.printf(" Total Balance: %10.2f%n", getTotalBalance()); notifyAll(); } /** *獲取所有帳戶余額的總和。 * @return 總平衡 */ public synchronized double getTotalBalance() { double sum = 0; for (double a : accounts) sum += a; return sum; } /** * 獲取銀行中的帳戶編號。 * @return 賬戶數量 */ public int size() { return accounts.length; } }
package synch2; /** * 這個程序展示了多線程如何安全地訪問一個數據結構,使用同步方法。 * @version 1.31 2015-06-21 * @author Cay Horstmann */ public class SynchBankTest2 { public static final int NACCOUNTS = 100; public static final double INITIAL_BALANCE = 1000; public static final double MAX_AMOUNT = 1000; public static final int DELAY = 10; public static void main(String[] args) { Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE); for (int i = 0; i < NACCOUNTS; i++) { int fromAccount = i; Runnable r = () -> { try { while (true) { int toAccount = (int) (bank.size() * Math.random()); double amount = MAX_AMOUNT * Math.random(); bank.transfer(fromAccount, toAccount, amount); Thread.sleep((int) (DELAY * Math.random())); } } catch (InterruptedException e) { } }; Thread t = new Thread(r); t.start(); } } }
實驗結果如下圖所示:
測試程序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(); } } |
存在問題:兩個線程各做各的
實驗結果如下圖所示:
修改後的代碼如下:
import javax.sql.rowset.spi.SyncFactory; class Cbank { private static int s=2000; public synchronized 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(); } }
實驗結果如下圖所示:
實驗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張票
public class Demo { public static void main(String[] args) { Mythread mythread = new Mythread(); Thread ticket1 = new Thread(mythread); Thread ticket2 = new Thread(mythread); Thread ticket3 = new Thread(mythread); ticket1.start(); ticket2.start(); ticket3.start(); } } class Mythread implements Runnable { int ticket = 1; boolean flag = true; @Override public void run() { while (flag) { try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } synchronized (this) { if (ticket <= 10) { System.out.println(Thread.currentThread().getName() + "窗口售:第" + ticket + "張票"); ticket++; } if (ticket > 10) { flag = false; } } } } }
實驗結果如下圖所示:
三、實驗總結
本周學習了同步線程的相關問題,了解了並發多線程的兩種解決方法。還有在同步方法中使用wait()、notify 和notifyAll()方法,使用wait()方法使本線程等待,暫時讓出CPU的使用權,並允許其它線程使用這個同步方法,這周學習的收獲很多。
201771010137 趙棟《面向對象程序設計(java)》第十七周學習總結