Balking模式(犹豫模式)

如果线程发现某个对象状态改变了,则放弃当前的工作。比如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){

        }
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值