Java发生在线程启动之前 [英] Java happend before thread start

查看:110
本文介绍了Java发生在线程启动之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在某处读到,启动一个线程对发生关系之前有一些特殊影响.现在我不确定我的代码是否保证关系发生之前发生,所以请启发我.

I read somewhere that starting a thread has some special effect on the happend before relationship. Now I'm not sure if my code gurantees the happend before relationship, so please enlighten me.

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

I have a Dispatcher thread and a Worker class implementing the Runnable interface. The Dispatcher thread creates a new instance of the Worker and fills a LinkedList in the Worker instance through the add method with elements.

然后分派器通过execute方法将Worker实例移交给ExecutorService.

Then the Dispatcher hands the Worker instance to a ExecutorService via the execute method.

然后,Worker类中的run方法开始访问和删除LinkedList中的内容.

Then the run method in the Worker class starts accessing and removing stuff from the LinkedList.

重新启动的Worker实例是否与调度程序留在的LinkedList状态相同?还是LinkedList处于某种不一致状态?我是否必须使用同步方法来填充LinkedList?

Does the freshly started instance of the Worker see the same state of the LinkedList as the Dispatcher left it in? Or could it be that LinkedList is in some inconsitent state? Will I have to fill the LinkedList in a sychronized method?

推荐答案

Java语言规范

启动线程的动作与启动的线程中的第一个动作同步.

如果动作x 与后续动作y同步,那么我们也有hb(x, y).

如果我们有两个动作xy,则写hb(x, y)表示x 发生在 y之前.

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

但是,根据您的描述,在您谈到执行程序时,尚不清楚这与您的情况是否相关,但没有解释该执行程序的创建时间或启动它的工作线程的时间.

However, from your description it is not clear whether that is relevant in your case, as you talk about an executor, but don't explain when that executor is created or its worker threads started.

相关的是以下摘录自执行器的JavaDoc :

内存一致性影响:线程之前的操作 将Runnable对象提交给Executor happen-before 开始执行,也许在另一个线程中进行.

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

Hence your code is safe, as long as the dispatcher thread no longer accesses the list after submitting the Runnable.

这篇关于Java发生在线程启动之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆