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. WPF之MahApps.Metro下载和WPF学习经验

    这几天一直在学习WPF的东西.刚开始以为和Winform一样.拖拽控件来进行布局.结果远远没有那么简单.很多东西都需要自己写.包括样式.今天给大家分享一个 MahApps.Metro. 首先在NuGe ...

  2. intel汇编笔记

    另一篇汇编学习笔记AT&T Assembly on Linux  (linux下) mov ax,bx     bx到ax 读数据过程:cpu通过地址线发送地址a,控制线向存储器发送读命令,存 ...

  3. win32 htmlayout dom操作demo

    之前两篇关于win32 htmlayout博文,记载了一个实现了简单的点击按钮弹出新窗口的demo,之后实践中发现,图形界面开发,最重要的还是要实现响应用户操作,改变原有界面的功能.比如说,界面上有一 ...

  4. 在UWP的XAML中使用原始类型

    问题: I'm trying to access the system namespace for StaticResource variables in XAML on UWP. Here's (m ...

  5. ring3下利用WMI监视进程创建(vc版)

    #include "stdafx.h" #define _WIN32_DCOM #include <iostream> using namespace std; #in ...

  6. Oracle数据库密码重置、导入导出库命令

    重置办法如下:打开CMD命令提示符,然后输入下面命令进行重置: 输入sqlplus /nolog,回车 SQL> conn /as sysdba 已连接: SQL>alter user s ...

  7. Elasticsearch 6.1.2 搭建及使用教程一

    安装包: es6.1.2 es-head 开发环境:jdk 1.8 搭建流程一一说明: 将下载好的es解压后找到如下图文件 打开后如下图所示配置(已添加详细注释): # 集群的名字 cluster.n ...

  8. jquery选择器集锦

    一,基本选择器: 1 2 3 4 $("#txtName");   $("#txt\\#b");//获取id为 txt#b的元素,\\为转义符 $(" ...

  9. 基于ASP.NET的新闻管理系统(三)代码展示

    5.1.1栏目部分 增加栏目(addLanMu.aspx): <html xmlns="http://www.w3.org/1999/xhtml"> <head  ...

  10. Storm 学习之路(二)—— Storm核心概念详解

    一.Storm核心概念 1.1 Topologies(拓扑) 一个完整的Storm流处理程序被称为Storm topology(拓扑).它是一个是由Spouts 和Bolts通过Stream连接起来的 ...