標籤:
Single Threaded Execution Pattern【獨木橋模式】
一:single threaded execution pattern的參與者
--->SharedResource(共用資源)
二:single threaded execution pattern模式什麼時候使用
--->多線程程式設計時
--->資料可被多個線程訪問的時候
--->共用資源狀態可能變化的時候
--->需要確保資料安全性的時候
三:single threaded execution pattern思考
--->synchronized一見到它,勢必保護著什麼公用資源的資料。保證資料安全,就得所有該保護的地方都得保護。
--->保護公用資源的資料的範圍叫臨界區,臨界區儘可能的小。提高效能。
--->程式設計的時候,一定要防止死結的發生。主要是同步方法的外部調用順序,防止交叉調用,多線程時,會發生死結。
案例:三個人來回通過一扇門,通過時記錄該人的姓名和地址。
門類(公用資源)
1 package com.yeepay.sxf.thread1; 2 /** 3 * 門類(代表著多線程程式訪問的公用資源) 4 * @author sxf 5 * 6 */ 7 public class Gate { 8 //計數器 9 private int counter=0;10 //通過這扇門的人的名字11 private String name;12 //正在通過這扇門的人的地址13 private String address;14 //通過這扇門的動作15 //存在多線程同時訪問該資源。(臨界區需要做同步)16 public synchronized void passGate(String name,String address){17 counter+=1;18 this.name=name;19 this.address=address;20 check();21 }22 //記錄通過這扇門的人的資訊23 @Override24 public String toString() {25 26 return "NO:"+counter+"人 name="+name+" address="+address;27 }28 29 //檢查,如果資料不完整,說明多線程程式的安全性掛掉。列印警示資訊30 private void check(){31 if(name.charAt(0)!=address.charAt(0)){32 System.out.println("**********breaken*******"+toString());33 }34 }35 }View Code
人類(線程類)
1 package com.yeepay.sxf.thread1; 2 /** 3 * 人類(不同的人代表不同的線程,訪問公用資源門) 4 * @author sxf 5 * 6 */ 7 public class UserThread implements Runnable { 8 //門 9 private final Gate gate;10 //當前的人名11 private final String myName;12 //當前的人的地址13 private final String myAddress;14 //線程的構造器15 public UserThread(Gate gate,String myName,String myAddress) {16 this.gate=gate;17 this.myName=myName;18 this.myAddress=myAddress;19 }20 21 //線程體22 @Override23 public void run() {24 System.out.println("UserThread.run() begin:"+myName);25 while (true) {26 gate.passGate(myName, myAddress);27 }28 29 }30 31 32 }View Code
測試類別(主線程)
1 package com.yeepay.sxf.thread1; 2 /** 3 * 測試類別 4 * @author sxf 5 * 6 */ 7 public class Test { 8 public static void main(String[] args) { 9 //先聲明一個門10 Gate gate=new Gate();11 12 //聲明三個線程13 Thread user1Thread=new Thread(new UserThread(gate, "Asxf", "Ahenan"));14 Thread user2Thread=new Thread(new UserThread(gate,"Bsxs","Bhenan"));15 Thread user3Thread=new Thread(new UserThread(gate,"Csxy","Chenan"));16 17 //啟動三個線程18 user1Thread.start();19 user2Thread.start();20 user3Thread.start();21 }22 }View Code
多線程程式設計學習(2)之single threaded execution pattern