您好,登錄后才能下訂單哦!
假設有四個人,頻繁地通過海關出口,規定每次只能通過一個人,通過一個人時,將通過海關的總人次加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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。