- 当现在不适合这个操作,或是没有必要进行这个操作时就直接放弃这个操作而回去。这个就是Balking模式。
- 例如王某在餐厅吃饭,当王某需要点餐时喊服务员需要点餐。当服务员A和B都注意到了王某点餐的示意,这时服务员B看到服务员A已经去响应了王某的点餐请求,所以服务员B就不会再过去响应王某的点餐请求。
- 相比guarded-suspension设计模式,这是一种更加消极的模式。服务不了直接离开了。
- 操作的数据类
public class BalkingData {
private final String fileName;
private String content;
private boolean changed;
public BalkingData(String fileName, String content) {
this.fileName = fileName;
this.content = content;
this.changed = true;
}
public synchronized void change(String newContent) {
this.content = newContent;
this.changed = true;
}
public synchronized void save() throws IOException {
if (!changed) {
return;
}
doSave();
this.changed = false;
}
private void doSave() throws IOException {
System.out.println(Thread.currentThread().getName() + " calls do save,content=" + content);
try (Writer writer = new FileWriter(fileName, true)) {
writer.write(content);
writer.write("\n");
writer.flush();
}
}
}
- 顾客类
public class CustomerThread extends Thread {
private final BalkingData balkingData;
private final Random random = new Random(System.currentTimeMillis());
public CustomerThread(BalkingData balkingData) {
super("Customer");
this.balkingData = balkingData;
}
@Override
public void run() {
try {
balkingData.save();
for (int i = 0; i < 20; i++) {
balkingData.change("No." + i);
Thread.sleep(random.nextInt(1000));
//如果这里运行,说明有离得比较近的服务员能服务
balkingData.save();
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
- 服务员类
public class WaiterThread extends Thread {
private final BalkingData balkingData;
public WaiterThread(BalkingData balkingData) {
super("Waiter");
this.balkingData = balkingData;
}
@Override
public void run() {
for (int i = 0; i < 200; i++) {
try {
balkingData.save();
Thread.sleep(1_000L);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
- 调用类
public class BalkingClient {
public static void main(String[] args) {
BalkingData balkingData = new BalkingData("C:\\workspace\\fortest\\balking.txt", "===BEGIN====");
new CustomerThread(balkingData).start();
new WaiterThread(balkingData).start();
}
}
-
结果
Snipaste_2020-10-06_22-06-33.png
网友评论