如果线程发现某个对象状态改变了,则放弃当前的工作。比如Word文档编辑时的Ctr +s与系统自动保存。
Balking模式主要是关注状态
例如:需要初始化系统全局资源,一旦初始化过了就不再加载
public synchronized HashMap load(){
if(hasLoad){
return hashMap;
}
hashMap = new HashMap();
/**
**装载资源
*/
}
模仿文档自动保存与手动ctrl +s
public class document{
private boolean changed;
private List<String> content = new ArrayList<String>();
private final FileWriter writer;
private static AutoSaveThread autoSaveThread;
private Document(String documentPath,String doucmentName){
this.writer = new FileWriter(new File(documentPath,documentName),true);
}
public static Document create(String documentPath,String documentName) throws IOException{
Document document = new Document(documentPaht,documentName);
autoSaveThread = new AutoSaveThread(document);
autoSaveThread.start();
return document;
}
public void edit(String content){
synchronized(this){
this.content.add(content);
this.changed = true;
}
}
public void close() throws IOException{
autoSaveThread.interrupt();
writer.close();
}
public void save() throws IOException{
synchronized(this){
if(!changed)
return;
System.out.println(Thread.currentThread()+"execute the save action")
for(String cacheLine : content){
this.writer.writer(cacheLine);
this.writer.writer("\r\n");
}
this.writer.flush();
this.changed = false;
this.content.clear();
}
}
}
public class AutoSaveThread extends Thread{
private Document document;
public AutoSaveThread(Document document){
this.document = document;
}
@Overried
public void run(){
while(true){
try{
TimeUnit.SECONDS.sleep(1);
document.save();
}catch(InterruptedException e){
}
}
}
}