多线程程序设计学习(2)之single threaded execution pattern

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     @Override
24     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     @Override
23     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
原文地址:https://www.cnblogs.com/shangxiaofei/p/4656189.html