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 }

 

posted on 2020-03-13 14:15  四维胖次  阅读(679)  评论(0编辑  收藏  举报