关于线程的问题
我只是在玩java中的线程。我有一个实现可运行的类。
public class MyThread implements Runnable{
private boolean finished;
//Other variables
public void run(){
//Thread code
}
}
我的理解是,MyThread 类型的每个线程都有自己的成员变量副本,并且写入这些成员变量不需要同步。这个假设正确吗?如果正确的话,访问什么内容需要同步?有人可以提供一个大纲或伪代码吗?谢谢。
I am just playing around with threads in java. I have a class which implements runnable.
public class MyThread implements Runnable{
private boolean finished;
//Other variables
public void run(){
//Thread code
}
}
My understanding is that each thread of type MyThread will have its own copy of member variables and writes to those member variables need not be synchronized. Is this assumption correct? If correct, access to what needs to be synchronized? Can someone care to give a outline or pseudo code.? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
未必。您可以使用同一个
MyThread
实例创建多个线程。例如:现在将有三个线程都在同一个对象中运行代码。
我建议您重命名
MyThread
,因为它不是线程 - 它是线程要执行的任务。这使得它更清楚(IMO)。Not necessarily. You could create multiple threads using the same instance of
MyThread
. For example:Now there will be three threads all running code in the same object.
I suggest you rename
MyThread
as it's not a thread - it's a task for a thread to perform. That makes it clearer (IMO).并发性的真正大索引跟踪 非常值得一读(是的,它有例子)。
The Really Big Index trail on concurrency is well worth a read (yes, it has examples).