加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java在线程启动之前发生

发布时间:2020-12-15 08:44:02 所属栏目:Java 来源:网络整理
导读:我在某处读到,开始一个线程对关系之前的事件有一些特殊的影响.现在我不确定我的代码是否在关系之前保证了这一点,所以请赐教. 我有一个Dispatcher线程和一个实现Runnable接口的Worker类. Dispatcher线程创建Worker的新实例,并通过带元素的add方法填充Worker实
我在某处读到,开始一个线程对关系之前的事件有一些特殊的影响.现在我不确定我的代码是否在关系之前保证了这一点,所以请赐教.

我有一个Dispatcher线程和一个实现Runnable接口的Worker类. Dispatcher线程创建Worker的新实例,并通过带元素的add方法填充Worker实例中的LinkedList.

然后,Dispatcher通过execute方法将Worker实例交给ExecutorService.

然后,Worker类中的run方法开始从LinkedList访问和删除东西.

新生成的Worker实例是否看到与Dispatcher一样的LinkedList状态?或者可能是LinkedList处于某种不一致的状态?我是否必须在同步方法中填充LinkedList?

解决方法

Java语言规范 writes:

An action that starts a thread synchronizes-with the first action in the thread it starts.

If an action x synchronizes-with a following action y,then we also have hb(x,y).

If we have two actions x and y,we write hb(x,y) to indicate that x happens-before y.

但是,根据您的描述,当您谈论执行程序时,不清楚这是否与您的情况相关,但不解释何时创建执行程序或其工作线程启动.

相关的是从Executor’s JavaDoc开始的以下内容:

Memory consistency effects: Actions in a thread prior to
submitting a Runnable object to an Executor
happen-before its execution begins,perhaps in another thread.

因此,只要调度程序线程在提交Runnable后不再访问列表,您的代码就是安全的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读