二十二、JAVA多线程笔记:Balking设计模式

如果现在不适合执行这个操作,或者没有必要执行这个操作,就停止处理,直接返回--这就是Balking模式。所谓Balk,就是停止并返回的意思。

Balking模式与Guarded Suspension模式一样,也存在守护条件,在Balking模式中,如果守护条件不成立,则立即中断处理。这与Guarded Suspension模式不同,因为Guarded Suspension模式是一直等待至可以运行。

某个线程因为发现其他线程正在执行相同的工作,而放弃即将开始的任务。

代码示例:

文档编辑&自动保存

package com.zl.step22;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static java.lang.Thread.currentThread;

// 代表正在编辑的文档类
public class Document {
    // 如果文档发生改变,changed变更为true,否则false
    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),false) ;

    }

    // 静态方法,用于创建文档,顺便启动自动保存文档的线程
    public static Document create(String documentPath , String documentName) throws IOException{
        Document document = new Document(documentPath,documentName );
        autoSaveThread = new AutoSaveThread(document);
        autoSaveThread.start();
        return document ;
    }

    // 文档编辑,其实就是往content队列中提交字符串
    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(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();

        }
    }

}
package com.zl.step22;

import java.util.concurrent.TimeUnit;

/**
 *
 * 每隔一秒,调用一次document的save方法
 */
public class AutoSaveThread  extends  Thread {

    private final Document document ;

    public AutoSaveThread(Document document){
        super("DocumnetAutoSaveThread .......");
        this.document = document ;
    }

    @Override
    public void run(){
        while (true) {

            try {
                document.save();
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
                break;
            }
        }
    }


}
package com.zl.step22;

import java.io.IOException;
import java.util.Scanner;

/**
 * 模拟自动编辑监控线程, 修改超过5次自动保存
 */
public class DocumentEditThread extends Thread {

    private final  String documnetPath ;

    private final  String getDocumnetName ;

    private final Scanner scanner = new Scanner(System.in) ;

    public DocumentEditThread(String documnetPath , String documnetName){
        super("DocumnetEditThread .... ");
        this.documnetPath = documnetPath ;
        this.getDocumnetName = documnetName;

    }

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

        try{
            Document document = Document.create(documnetPath,getDocumnetName);

            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){
            throw new RuntimeException() ;
        }

    }

}
package com.zl.step22;

public class BalkingTest {

    public static void main(String[] args) {
        new DocumentEditThread("/A","balking.txt").start(); ;
    }

}

代码运行:

生成文件:

文件内容

猜你喜欢

转载自blog.csdn.net/zhanglong_4444/article/details/86473811
今日推荐