我是靠谱客的博主 负责海燕,这篇文章主要介绍Java多线程 对象未完成初始化就把对象提供给外界--注册监听器(观察者模式),现在分享给大家,希望可以做个参考。

文章目录

      • 注册监听器

注册监听器

运用观察者模式 注册监听器导致的对象未完成初始化就把对象提供给外界 的代码如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.thread.background; /** * 类名称:EventListenerError * 类描述: 运用观察者模式 注册监听器导致的对象未完成初始化就把对象提供给外界 * * @author: https://javaweixin6.blog.csdn.net/ * 创建时间:2020/9/1 20:34 * Version 1.0 */ public class EventListenerError { int count; public EventListenerError(MySource source) { //匿名内部类的方式 , 创建 EventListener接口实例 source.registerListener(new EventListener() { @Override public void onEvent(Event e) { //监听器, 监听到东西的时候, 就打印获取的值 System.out.println("n我得到的数字是 "+count); } }); //模拟其他业务逻辑 for (int i = 0; i < 10000; i++) { System.out.print(i); } //count初始化 count = 100; } public static void main(String[] args) { MySource mySource = new MySource(); new Thread(() -> { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } mySource.eventCome(new Event() { }); }).start(); EventListenerError eventListenerError = new EventListenerError(mySource); } static class MySource { private EventListener listener; void registerListener(EventListener eventListener) { this.listener = eventListener; } /** * 每次有事件来临的时候, 触发eventCome方法 * @param e */ void eventCome(Event e) { if (listener != null) { listener.onEvent(e); } else { System.out.println("还未初始化完毕! "); } } } interface EventListener { void onEvent(Event e); } interface Event { } }

运行程序后 ,结果如下 . 原本期望结果是100的, 得到的count结果却是0 .


主要的原因是, 在此注册监听器的代码, onEvent方法中, 已经隐含的暴露了外部类的对象.
new EventListener()是匿名内部类, 而这个匿名内部类持有外部类的引用, 因此可以对count直接的打印, 修改等操作, 那么如果对count赋值的操作还没完成, 即便是注册监听器看似安全的动作, 实际上也有安全隐患.

最后

以上就是负责海燕最近收集整理的关于Java多线程 对象未完成初始化就把对象提供给外界--注册监听器(观察者模式)的全部内容,更多相关Java多线程内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(73)

评论列表共有 0 条评论

立即
投稿
返回
顶部