多线程学习之一独木桥模式Single Threaded Execution Pattern

Single Threaded Execution Pattern【独木桥模式】

一:single threaded execution pattern的参与者
--->SharedResource(共享资源)

二:single threaded execution pattern模式什么时候使用
--->多线程程序设计时
--->数据可被多个线程访问的时候
--->共享资源状态可能变化的时候
--->需要确保数据安全性的时候

三:single threaded execution pattern思考
--->synchronized一见到它,势必保护着什么公共资源的数据。保证数据安全,就得所有该保护的地方都得保护。
--->保护公共资源的数据的范围叫临界区,临界区尽可能的小。提高性能。
--->程序设计的时候,一定要防止死锁的发生。主要是同步方法的外部调用顺序,防止交叉调用,多线程时,会发生死锁。

案例:三个人来回通过一扇门,通过时记录该人的姓名和地址。

门类(公共资源)

 1 /**
 2  * 
 3  */
 4 package com.benxq.thread2;
 5 
 6 /**
 7  * 门类:代表需要访问的公共资源
 8  * Created by qucf on 2015年10月22日. 
 9  */
10 public class Gate {
11     //计数器
12     private int count=0;
13     
14     //通过这扇们的名字
15     private String name;
16     
17     //正在通过这扇们的人的地址
18     private String address;
19     
20     //通过这扇门的动作,存在多线程同事访问该资源,(临界区需要做同步)
21     public synchronized void passGate(String name,String address){
22         count++;
23         this.name=name;
24         this.address=address;
25         check();
26     }
27     //检查数据完整性,如果数据不完整说明程序的安全性已经挂掉,打印报警信息
28     private void check(){
29         if(name.charAt(0)!=address.charAt(0)){
30             System.out.println("========错误========"+count+"人 name="+name+"通过时发生数据不完整");
31         }
32     }
33 }
View Code

人类(线程类)

 1 /**
 2  * 
 3  */
 4 package com.benxq.thread2;
 5 
 6 /**
 7  * Created by qucf on 2015年10月22日. 
 8  */
 9 public class UserThread implements Runnable{
10 
11     //
12     private Gate gate;
13     
14     //当前人的名称
15     private String name;
16     
17     //地址
18     private String address;
19     
20     public UserThread(Gate gate,String name,String address){
21         this.gate=gate;
22         this.name=name;
23         this.address=address;
24     }
25     
26     @Override
27     public void run() {
28         System.out.println("通过人:"+name);
29         while(true){
30             gate.passGate(name, address);
31         }
32     }
33 
34 }
View Code

测试类(主线程)

 1 /**
 2  * 
 3  */
 4 package com.benxq.thread2;
 5 
 6 import java.util.concurrent.ExecutorService;
 7 import java.util.concurrent.Executors;
 8 
 9 /**
10  * 测试类
11  * Created by qucf on 2015年10月22日. 
12  */
13 public class Test {
14 
15     public static void main(String[] args) {
16         //创建一个门
17         Gate gate=new Gate();
18         
19         //创建一个线程池
20         ExecutorService es=Executors.newFixedThreadPool(10);
21         for (int i = 0; i < 10; i++) {
22             es.submit(new UserThread(gate, "Zhansan"+i, "Z地址"+i));
23         }
24         
25     }
26 }
View Code
原文地址:https://www.cnblogs.com/quchengfeng/p/4901131.html