zoukankan      html  css  js  c++  java
  • Java 并发编程——实现可监听线程

     1 package cn.pancc.purejdk.concurrent;
     2 
     3 import java.util.Objects;
     4 import java.util.concurrent.CopyOnWriteArrayList;
     5 
     6 /**
     7  * The type Notifying thread.
     8  *
     9  * @author pancc
    10  * @version 1.0
    11  */
    12 public abstract class AbstractNotifyingThread extends Thread {
    13     /**
    14      * COW 模式
    15      */
    16     CopyOnWriteArrayList<Listener> listeners = new CopyOnWriteArrayList<>();
    17 
    18     private String msg = "success";
    19 
    20     public String getMsg() {
    21         return msg;
    22     }
    23 
    24     /**
    25      * The interface Listener.
    26      */
    27     interface Listener {
    28         /**
    29          * Call back.
    30          *
    31          * @param notifyObject the notify object
    32          */
    33         void callBack(final AbstractNotifyingThread notifyObject);
    34     }
    35 
    36     public void addListener(Listener listener) {
    37         this.listeners.add(Objects.requireNonNull(listener));
    38     }
    39 
    40     public void removeListener(Listener listener) {
    41         this.listeners.remove(Objects.requireNonNull(Objects.requireNonNull(listener)));
    42     }
    43 
    44     @Override
    45     public void run() {
    46         try {
    47             doRun();
    48         } catch (Exception e) {
    49             // 设置标识为失败
    50             msg = "fail";
    51         } finally {
    52             notifyListeners();
    53         }
    54     }
    55 
    56     private void notifyListeners() {
    57         this.listeners.forEach(listener -> listener.callBack(this));
    58     }
    59 
    60     /**
    61      * 实际执行的内容。无论是否抛出异常,{@link #notifyListeners}都会正常执行
    62      *
    63      * @see Runnable#run()
    64      */
    65     protected abstract void doRun();
    66 
    67     public static void main(String[] args) {
    68         AbstractNotifyingThread thread = new AbstractNotifyingThread() {
    69             @Override
    70             protected void doRun() {
    71                 int count = 5;
    72                 for (int i = 0; i < count; i++) {
    73                     if (i == 3) {
    74                         throw new RuntimeException("=3");
    75                     }
    76                     System.out.println(i);
    77                 }
    78             }
    79         };
    80         thread.addListener(t -> System.out.println("task status: " + t.getMsg()));
    81         thread.start();
    82     }
    83 }
  • 相关阅读:
    【原】如何实现IE6下块级元素的内容自动收缩
    【原】常见的模块,你语义化了没
    【转】CSS Nuggest
    那年,寻找工作的历程
    前端开发小工具SuperApp——Ctrl+S自动刷新浏览器
    【转】在html中引入CSS的方法
    HTML中常用的实体字符
    imemode:disabled 禁止表单使用文本框输入法
    【原】工作中常用win7快捷键
    复制本地文件完整路径
  • 原文地址:https://www.cnblogs.com/siweipancc/p/12486184.html
Copyright © 2011-2022 走看看