Balking Pattern的适用性:
1.不需要刻意执行的时候,balk可以提高性能
2.不想等待警戒条件成立的时候
3.警戒条件只需第一次成立的时候,例如初始化操作
例子:仅类似“自动保存功能”,通过此模式,防止重复保存。
所需的类:
Date:数据类;
AutosaverThread:定期自动保存数据的线程类;
ChngsaverThread:自己修改并保存的线程类;
Main:测试类
//Date.java
import java.io.FileWriter; import java.io.IOException; public class Date { public final String filename; //保存的文件名 public String context; //保存的内容 public boolean changedFlag; //若内容修改后,没被保存,则为true public Date(String filename , String context){ this.filename = filename; this.context = context; this.changedFlag = true; } //内容修改方法 public synchronized void change(String newcontext){ context = newcontext; changedFlag = true; } //若内容有修改,则保存 public synchronized void save() throws IOException{ if(!changedFlag){ //警戒条件 return; //即balk操作,若已保存或未修改,则终止操作 } doSave(); changedFlag = false; } //实际将数据保存到文件中的方法 public void doSave() throws IOException{ System.out.println(Thread.currentThread().getName() + " calls doSave, context:" + context); FileWriter fw = new FileWriter(filename); fw.write(context); fw.close(); } }
//AutosaverThread.java
import java.io.IOException; public class AutosaverThread extends Thread{ private Date date; AutosaverThread(String name , Date date){ super(name); this.date = date; } public void run(){ try{ while(true){ date.save(); Thread.sleep(1000); } }catch(InterruptedException e){ e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); } } }
//ChngsaverThread.java
import java.io.IOException; import java.util.Random; public class ChngsaverThread extends Thread{ private Date date; private Random random = new Random(); ChngsaverThread(String name , Date date){ super(name); this.date = date; } public void run(){ for(int i=1; i<21; i++){ try { date.change("he is fang" + i); Thread.sleep(random.nextInt(1000)); date.save(); } catch (InterruptedException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } } } }
//Main.java
public class Main { public static void main(String[] args) { Date date = new Date("d.txt", "i am lulu "); new AutosaverThread("AAAAthread", date).start(); new ChngsaverThread("CCCCthread", date).start(); } }