import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

public class Test {
    public static void main(String[] args){
        BalkingTest.test();
    }
}

/*
    22.2 Balking模式之文档编辑

    多个线程监控某个共享变量,A线程监控到共享变量发生变化后即立即触发某个动作,但是
    此时发现另外一个线程B已经针对该变量的变化开始了行动,因此A便放弃了准备开始的工作
    ,我们把这种线程间交互称作Balking(犹豫)设计模式

        ——简而言之,就是当你去获取临界区资源时,发现正有人在使用着,那么你没有阻塞
            而是放弃了去获取这部分的资源。你认定,别的线程已经开始了对这部分资源的
            修改操作,所以你无需操作。
 */
class Document{
    private boolean changed = false;

    private List<String> content = new ArrayList<>();

    private final FileWriter writer;

    private static AutoSaveThread autoSaveThread;

    private Document(String documentPath, String documentName)
        throws IOException {
        this.writer = new FileWriter(new File(documentPath,documentName),true);
    }

    public static Document create(String documentPath, String documentName)
        throws IOException{
        Document document = new Document(documentPath,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.write(cacheLine);
                this.writer.write("\r\n");
            }
            this.writer.flush();
            this.changed=false;
            this.content.clear();
        }
    }
}

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 (InterruptedException|IOException e) {
                break;
            }
        }
    }
}

class DocumentEditThread extends Thread{
    private final String documentPath;
    private final String documentName;
    private final Scanner scanner = new Scanner(System.in);

    public DocumentEditThread(String documentPath, String documentName) {
        super("DocumentEditThread");
        this.documentPath = documentPath;
        this.documentName = documentName;
    }

    @Override
    public void run() {
        int times = 0;

        try{
            Document document = Document.create(documentPath,documentName);
            while (true) {
                String text = scanner.next();
                if("quit".equals(text)){
                    document.close();
                    break;
                }
                document.edit(text);
                if (times == 5) {
                    document.save();
                    times=0;
                }
                times++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class BalkingTest{
    public static void test(){
        new DocumentEditThread(".","temp.tmp").start();
    }
}

Balking设计模式的更多相关文章

  1. java多线程12设计模式

    1.Single Threaded Execution Pattern(单线程运行模式) 2.Immutable Pattern(一成不变的模式) 3.Guarded Suspension Patte ...

  2. MVVM设计模式和WPF中的实现(四)事件绑定

    MVVM设计模式和在WPF中的实现(四) 事件绑定 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二)数据绑定 MVVM模式解析和在WPF中 ...

  3. java EE设计模式简介

    1.何为设计模式 设计模式提供了对常见应用设计问题的解决方案.在面向对象的编程中,设计模式通常在解决与对象创建和交互相关的问题,而非整体软件架构所面对的大规模问题,它们以样板代码的形式提供了通用的解决 ...

  4. 计算机程序的思维逻辑 (54) - 剖析Collections - 设计模式

    上节我们提到,类Collections中大概有两类功能,第一类是对容器接口对象进行操作,第二类是返回一个容器接口对象,上节我们介绍了第一类,本节我们介绍第二类. 第二类方法大概可以分为两组: 接受其他 ...

  5. 《JavaScript设计模式 张》整理

    最近在研读另外一本关于设计模式的书<JavaScript设计模式>,这本书中描述了更多的设计模式. 一.创建型设计模式 包括简单工厂.工厂方法.抽象工厂.建造者.原型和单例模式. 1)简单 ...

  6. 《JavaScript设计模式与开发实践》整理

    最近在研读一本书<JavaScript设计模式与开发实践>,进阶用的. 一.高阶函数 高阶函数是指至少满足下列条件之一的函数. 1. 函数可以作为参数被传递. 2. 函数可以作为返回值输出 ...

  7. 设计模式之行为类模式大PK

                                        行为类模式大PK 行为类模式包括责任链模式.命令模式.解释器模式.迭代器模式.中介者模式.备忘录模式.观察者模式.状态模式.策略 ...

  8. .NET设计模式访问者模式

    一.访问者模式的定义: 表示一个作用于某对象结构中的各元素的操作.它使你可以在不改变各元素类的前提下定义作用于这些元素的新操作. 二.访问者模式的结构和角色: 1.Visitor 抽象访问者角色,为该 ...

  9. Java开发中的23种设计模式详解

    [放弃了原文访问者模式的Demo,自己写了一个新使用场景的Demo,加上了自己的理解] [源码地址:https://github.com/leon66666/DesignPattern] 一.设计模式 ...

随机推荐

  1. eclipse 插件编写(三)

    参考:http://help.eclipse.org/mars/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Fguide%2Fworkbench_ ...

  2. List<T>多字段排序的一个通用类

    本文中的方法旨在解决通用的问题,非常注重效率的地方,还应该针对具体的类去写排序方法. 废话不多说,直接上代码 具体使用场景: 要排序的类 1 public class bb 2 { 3 public ...

  3. Tensorflow数据读取机制

    展示如何将数据输入到计算图中 Dataset可以看作是相同类型"元素"的有序列表,在实际使用时,单个元素可以是向量.字符串.图片甚至是tuple或dict. 数据集对象实例化: d ...

  4. autotools工具使用 good

    学习GNU/LINUX开发的编程人员,上手之后不久就会在编译开源软件的时候碰到configure脚本,过段时间还会知道configure脚本是 autoconf生成的:但是真正想用起来autoconf ...

  5. 如何把zip文件直接解压到内存里?

    解压到硬盘再读进来耽误时间. var  LZip: TZipFile;  LMem: TMemoryStream;  LBytes: TBytes;begin  LZip := TZipFile.Cr ...

  6. 使用mingw 对libcURL,openSSL,zLib交叉编译

    使用mingw 对libcURL,openSSL,zLib交叉编译   将三个库解压到同一目录下 比如取目录名为 "source" 的目录   提前安装active-perl 配置 ...

  7. 学习Java,值得你留意的问题(1)更名为《学习Java,容易被你忽略的小细节(1)》

    记得大二快要结束的时候,有个女孩子突然问我“你会Java吗,帮我做大作业好吗?” 实话说,那个女孩真的很漂亮,我当时也非常想帮她.但是我从来没有接触过Java,让我在短短的几天内完成Java程序设计课 ...

  8. ngnix 安装

    1安装PCRE库 ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/ 下载最新的 PCRE 源码包,使用下面命令下载编译和安装 PCRE 包: ...

  9. 3017C语言_文件

    第七章  文件 7.1  C语言文件的概念 7.1.1 文件的概念 在此之前,所有的输入和输出只涉及到键盘和显示器.在运行C程序时,我们通过键盘输入数据并借助显示器把程序的运算结果显示出来.但是,计算 ...

  10. 【LEETCODE】32、LeetCode的第35题,查找插入的位置

    凉凉,看来想做好一个题还不容易啊... 有点难受... 1.看看题目吧 Given a sorted array and a target value, return the index if the ...