Single Thread Execution设计模式

Single Thread Execution模式是指在同一时刻只能有一个线程去访问共享资源,即采用排他方式的操作保证在同一个时刻只能有一个线程访问共享

资源。线程安全类是指多个线程在对某个类的实例同时进行操作时,不会引起数据的不一致问题。反之,就是非线程安全的类。子类如果继承了线程安全的类并且打破了Single Thread Execution的方式,就会破坏安全性,这种情况一般称为继承异常。在这个模式中,synchronized关键字起到了决定性的作用,但是排他性是以牺牲性能为代价的,在保证线程安全的前提下,尽量缩小synchronized的作用域。

    使用Single Thread Execution模式的场景:

  • 多线程访问资源时,被synchronized同步的方法总是排他的。

  • 多个线程对某个类状态发生改变的时候

示例代码:

public class FlightSecurity {
private int count=0;
private String boardingPass="null";
private String idCard="null";

private void check() {
if(this.boardingPass.charAt(0)!=this.idCard.charAt(0)) {
throw new RuntimeException("========Exception========"+toString());
}
}

public synchronized void pass(String boardingPass, String idCard) {
this.boardingPass=boardingPass;
this.idCard=idCard;
this.count++;
check();
toString();
}

public String toString() {
return "The "+this.count+" passengers,boardingPass ["+this.boardingPass+"],idCard ["+this.idCard+"]";
}

}
public class FlightSecurityTest {
static class Passengers extends Thread{
private final FlightSecurity flightSecurity;
private final String idCard;
private final String boardingPass;
public Passengers(FlightSecurity flightSecurity,String idCard,String boardingPass) {
this.flightSecurity=flightSecurity;
this.idCard=idCard;
this.boardingPass=boardingPass;
}
@Override
public void run() {
//while(true) {
flightSecurity.pass(boardingPass, idCard);
//}
}
}

public static void main(String[] args) {
final FlightSecurity flightSecurity=new FlightSecurity();
new Passengers(flightSecurity,"A123456","AF123456").start();
new Passengers(flightSecurity,"B123456","BF123456").start();
new Passengers(flightSecurity,"C123456","CF123456").start();
}

}

你可能感兴趣的:(2022技术栈系列,java,设计模式,java,jvm)