1,什么是Balking?
类似放弃作用,即本身有个线程准备响应时,发现另外一个线程已经响应,故当前线程放弃响应。
2,代码举例:
自动保存和手动保存
文档类
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static java.lang.Thread.currentThread;
/**
* 文档,表示当前正在操作的文档
*/
public class Document {
//如果文档改变,changed会被设置为true
private boolean changed = false;
//需要保存的内容
private List<String> contents = new ArrayList();
private final FileWriter writer;
//自动保存文档的线程
private static AutoSaveThread autoSaveThread;
//构造函数,传入文档的路径和名称
private Document(String path,String name) throws IOException {
this.writer = new FileWriter(new File(path,name));
}
//创建文档
public static Document create(String path,String name) throws IOException {
Document document = new Document(path,name);
autoSaveThread = new AutoSaveThread(document);
autoSaveThread.start();
return document;
}
//编辑文档
public void edit(String content){
synchronized (this){
this.contents.add(content);
//文档改变
this.changed = true;
}
}
//文档关闭时,中断文档自动保存线程,然后关闭writer流
public void close() throws Exception{
autoSaveThread.interrupt();
writer.close();
}
//保存文档
public void save() throws IOException {
synchronized (this){
//没有改变,就不执行。balking
if(!changed){
return;
}
System.out.println(currentThread() + "执行保存任务");
//将内容写入
for(String content:contents){
this.writer.write(content);
this.writer.write("\r\n");
}
this.writer.flush();
this.changed = false;
this.contents.clear();
}
}
}
自动保存线程
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class AutoSaveThread extends Thread {
private final Document document;
public AutoSaveThread(Document document) {
super("DocumentAutoSaveThread");
this.document = document;
}
@Override
public void run() {
while (true){
try{
document.save();
TimeUnit.SECONDS.sleep(1);
} catch (IOException| InterruptedException e) {
e.printStackTrace();
break;
}
}
}
}
文档编辑线程
import java.util.Scanner;
public class DocumentEditThread extends Thread {
private final String path;
private final String name;
private final Scanner scanner = new Scanner(System.in);
public DocumentEditThread(String path,String name){
super("DocumentEditThread");
this.path = path;
this.name = name;
}
@Override
public void run() {
int time = 0;
try{
Document document = Document.create(path,name);
while (true){
String text = scanner.next();
if("quit".equals(text)){
document.close();
break;
}
document.edit(text);
if(time == 5){
document.save();
time = 0;
}
time++;
}
}catch (Exception e){
throw new RuntimeException(e);
}
}
}
测试类
public class BalkingTest {
public static void main(String[] args) {
new DocumentEditThread("./","balking.txt").start();
}
}
本文深入探讨了Balking设计模式,通过一个文档编辑与自动保存的案例,详细讲解了如何利用该模式避免不必要的资源消耗。文章展示了如何在多线程环境中,通过检查状态来决定是否执行操作,从而实现资源的有效利用。

776

被折叠的 条评论
为什么被折叠?



