关于线程的问题

发布于 2024-09-08 18:29:51 字数 307 浏览 3 评论 0原文

我只是在玩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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

少女七分熟 2024-09-15 18:29:51

未必。您可以使用同一个 MyThread 实例创建多个线程。例如:

MyThread x = new MyThread();
new Thread(x).start();
new Thread(x).start();
new Thread(x).start();

现在将有三个线程都在同一个对象中运行代码。

我建议您重命名 MyThread,因为它不是线程 - 它是线程要执行的任务。这使得它更清楚(IMO)。

Not necessarily. You could create multiple threads using the same instance of MyThread. For example:

MyThread x = new MyThread();
new Thread(x).start();
new Thread(x).start();
new Thread(x).start();

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).

情话难免假 2024-09-15 18:29:51
  • 每个 MyThread 实例都是一个新实例,就像普通的类和对象一样。
  • 复制本机类型的变量。这意味着更改一个线程中的变量不会对另一线程产生任何影响。这些不必同步。
  • 对于对象,其引用被复制。这意味着两个线程可能拥有对同一对象的引用。如果两个线程同时操作该对象,这可能会变得很糟糕。因此,这些访问必须同步。
  • Each MyThread instance is a new instance, just like normal classes and objects.
  • Variables of native types are copied. This means that changing the variable in one thread does nothing to the other thread. These do not have to be synchronized.
  • For objects their references are copied. This means that two threads may have a reference to the same object. If the two threads manipulate that object at the same time, this can go bad. Therefore, these accesses have to be synchronized.
浅黛梨妆こ 2024-09-15 18:29:51

并发性的真正大索引跟踪 非常值得一读(是的,它有例子)。

The Really Big Index trail on concurrency is well worth a read (yes, it has examples).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文