编程语言
首页 > 编程语言> > Java在线程启动之前发生

Java在线程启动之前发生

作者:互联网

我在某处读到,开始一个线程对关系之前的事件有一些特殊的影响.现在我不确定我的代码是否在关系之前保证了这一点,所以请赐教.

我有一个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后不再访问列表,您的代码就是安全的.

标签:java-memory-model,java,concurrency,jvm,synchronization
来源: https://codeday.me/bug/20190729/1576538.html