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

时间:2024-10-06 18:07:56

Single Threaded Execution Pattern【独木桥模式】

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

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

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

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

门类(公共资源)

 package com.yeepay.sxf.thread1;
/**
* 门类(代表着多线程程序访问的公共资源)
* @author sxf
*
*/
public class Gate {
//计数器
private int counter=0;
//通过这扇门的人的名字
private String name;
//正在通过这扇门的人的地址
private String address;
//通过这扇门的动作
//存在多线程同时访问该资源。(临界区需要做同步)
public synchronized void passGate(String name,String address){
counter+=1;
this.name=name;
this.address=address;
check();
}
//记录通过这扇门的人的信息
@Override
public String toString() { return "NO:"+counter+"人 name="+name+" address="+address;
} //检查,如果数据不完整,说明多线程程序的安全性挂掉。打印报警信息
private void check(){
if(name.charAt(0)!=address.charAt(0)){
System.out.println("**********breaken*******"+toString());
}
}
}

人类(线程类)

 package com.yeepay.sxf.thread1;
/**
* 人类(不同的人代表不同的线程,访问公共资源门)
* @author sxf
*
*/
public class UserThread implements Runnable {
//门
private final Gate gate;
//当前的人名
private final String myName;
//当前的人的地址
private final String myAddress;
//线程的构造器
public UserThread(Gate gate,String myName,String myAddress) {
this.gate=gate;
this.myName=myName;
this.myAddress=myAddress;
} //线程体
@Override
public void run() {
System.out.println("UserThread.run() begin:"+myName);
while (true) {
gate.passGate(myName, myAddress);
} } }

测试类(主线程)

 package com.yeepay.sxf.thread1;
/**
* 测试类
* @author sxf
*
*/
public class Test {
public static void main(String[] args) {
//先声明一个门
Gate gate=new Gate(); //声明三个线程
Thread user1Thread=new Thread(new UserThread(gate, "Asxf", "Ahenan"));
Thread user2Thread=new Thread(new UserThread(gate,"Bsxs","Bhenan"));
Thread user3Thread=new Thread(new UserThread(gate,"Csxy","Chenan")); //启动三个线程
user1Thread.start();
user2Thread.start();
user3Thread.start();
}
}