Single Thread Execution设计模式

2023-12-14 08:25:53

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();
}

}

文章来源:https://blog.csdn.net/seacean2000/article/details/134964897
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。