单线程执行模式
场景:有一个门,记录每次进入们的用户的姓名和来历
package com.ln.concurrent.chapter5;
/**
* @ProjectName: java-concurrency
* @Package: com.ln.concurrent.chapter5
* @version: 1.0
*/
/**
* @ClassName:Gate
* @Author:linianest
* @CreateTime:2020/3/24 9:06
* @version:1.0
* @Description TODO: 定义共享资源
*/
/**
* SharedResource
*/
public class Gate {
private int counter = 0;
private String name = "NoBody";
private String address = "NoWhere";
/**
* 临界值
* @param name
* @param address
*/
public synchronized void pass(String name, String address) {
this.counter++;
this.name = name;
this.address = address;
verify();
}
private void verify() {
if (this.name.charAt(0) != this.address.charAt(0)) {
System.out.println("************BROKEN**************" + toString());
}
}
@Override
public String toString() {
return "NO." + counter + ":" + name + "," + address;
}
}
package com.ln.concurrent.chapter5;
/**
* @ProjectName: java-concurrency
* @Package: com.ln.concurrent.chapter5
* @version: 1.0
*/
/**
* @ClassName:User
* @Author:linianest
* @CreateTime:2020/3/24 9:11
* @version:1.0
* @Description TODO: 定义调用资源的线程
*/
public class User extends Thread {
private final String myName;
private final String myAdress;
private final Gate gate;
private static volatile int number;
public User(String myName, String myAdress, Gate gate) {
this.myName = myName;
this.myAdress = myAdress;
this.gate = gate;
}
@Override
public void run() {
System.out.println(myName + " BEGIN");
while (true) {
this.gate.pass(myName, myAdress);
try {
Thread.sleep(1_000L);
System.out.println("the thread " + Thread.currentThread().getName() + " coming ,the number is " + (number++));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package com.ln.concurrent.chapter5;
/**
* @ProjectName: java-concurrency
* @Package: com.ln.concurrent.chapter5
* @version: 1.0
*/
/**
*@ClassName:Client
*@Author:linianest
*@CreateTime:2020/3/24 9:17
*@version:1.0
*@Description TODO: 实现一个资源每次只有一个线程访问
*/
public class Client {
public static void main(String[] args) {
Gate gate = new Gate();
User bj = new User("Baobao","Beijin",gate);
User sh = new User("ShangLao","ShangHai",gate);
User gz = new User("GuangLao","GuangZhou",gate);
bj.start();
sh.start();
gz.start();
}
}
通过加锁的方式实现资源每次只能被一个线程访问