简体   繁体   中英

Question on threads

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.

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

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

关于并发的Really Big Index跟踪非常值得一读(是的,它有示例)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM