多线程Balking设计模式
import java.io.FileWriter;import java.io.Writer;public class BalkingData {
private boolean change = false;
private String content;
private final String fileName;
public BalkingData(String content, String fileName) {
this.change = true;
this.content = content;
this.fileName = fileName;
}
public void change(String content) {
synchronized (this) {
this.content = content;
this.change = true;
}
}
public void save() throws Exception {
synchronized (this) {
if (!change) {
return;
}
doSave();
change = false;
}
}
private void doSave() throws Exception {
System.out.println(Thread.currentThread().getName() + " calls do save,content=" + content);
Thread.sleep(1000);
try (Writer writer = new FileWriter(fileName, true)) {
writer.write(content);
writer.write("
");
writer.flush();
}
}
}
package com.thread.ch12;import java.util.Random;
public class CustomerThread extends Thread {
private final BalkingData balkingData;
private 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(1000);
balkingData.save();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.thread.ch12;import java.util.Random;
public class WaterThread extends Thread {
private final BalkingData balkingData;
private Random random = new Random(System.currentTimeMillis());
public WaterThread(BalkingData balkingData) {
super("Water");
this.balkingData = balkingData;
}
@Override
public void run() {
try {
for (int i = 0; i < 200; i++) {
balkingData.save();
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.thread.ch12;public class BalkingClient {
public static void main(String[] args) {
BalkingData balkingData = new BalkingData("dsds","F:\n.txt");
CustomerThread customerThread = new CustomerThread(balkingData);
WaterThread waterThread = new WaterThread(balkingData);
customerThread.start();
waterThread.start();
}
}
运行结果
Customer calls do save,content=dsds
Customer calls do save,content=NO.0
Customer calls do save,content=NO.1
Water calls do save,content=NO.2
Water calls do save,content=NO.3
Customer calls do save,content=NO.4
Water calls do save,content=NO.5
Water calls do save,content=NO.6
Customer calls do save,content=NO.7
Water calls do save,content=NO.8
Water calls do save,content=NO.9
Customer calls do save,content=NO.10
Water calls do save,content=NO.11
Customer calls do save,content=NO.12
Water calls do save,content=NO.13
Customer calls do save,content=NO.14
Water calls do save,content=NO.15
Customer calls do save,content=NO.16
Water calls do save,content=NO.17
Customer calls do save,content=NO.18
Customer calls do save,content=NO.19
Process finished with exit code -1
以上是 多线程Balking设计模式 的全部内容, 来源链接: utcz.com/z/513739.html