假设有四个人,频繁地通过海关出口,规定每次只能通过一个人,通过一个人时,将通过海关的总人次加1,同时记录该次通过人的姓名和出生地,如果出生地和名字不一致,不允许通过。
package com.jane.service;
/**
* 海关入口
*/
public class GateWay {
private int counter = 0;
private String name = "无名";
private String address = "无地址";
#
/**
* 通行
* @param name
* @param address
*/
public void pass(String name, String address) {
this.counter++;
this.name = name;
this.address = address;
checkPassport();
}
/**
* 检查护照
*/
private void checkPassport() {
//名字和地址匹配上才能通过
if(!this.name.equals(this.address)) {
System.out.println("禁止通行:" + "第" + this.counter + "人,姓名:" + this.name + ",来自:" + this.address);
}
}
}
package com.jane.service;
/**
* 人模拟线程,循环入关
*/
public class Person extends Thread{
private final GateWay gateWay;
private final String name;
private final String address;
public Person(GateWay gateWay, String name, String address) {
this.gateWay = gateWay;
this.name = name;
this.address = address;
}
public void run() {
System.out.println(this.name + ",开始入关");
while(true) {
this.gateWay.pass(this.name, this.address);
}
}
}
System.out.println("开始入关");
GateWay gate = new GateWay();
new Person(gate, "张三", "张三").start();
new Person(gate, "李四", "李四").start();
new Person(gate, "王五", "王五").start();
new Person(gate, "赵六", "赵六").start();
线程不安全!!!!!!!!!!!!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。