Threading and synchronized methods

走远了吗. 提交于 2019-12-02 06:18:51

问题


I have the following code:

public class MyThread extends Thread {
    private int i;
    public static int sum=0;
    public MyThread(int k){
      i=k;
    }




    public static void main(String[] args) throws InterruptedException{

       Thread t=new MyThread(1);
       Thread s=new MyThread(2);
       Thread p=new MyThread(3);
       t.start();
       s.start();       
    }


public synchronized void doSomething(){
    for(int i=0; i<100000; i++){
        System.out.println(this.i);
    }

}

    @Override
    public void run() {
        doSomething();

    }
}

the doSomething is synchronized. why is the output random? My assumption that the synchronized method would be the same as the synchronized block but the output of the block is sync and the method isn't.


回答1:


The synchronized keyword there prevents synchronized method calls on the same object from being interleaved. It does not prevent interleaving method calls on different objects. Since you have three different objects, the three calls can run simultaneously.

You need to synchronize on a single object which is shared by all three threads.




回答2:


The synchronization on methods only holds for invocations of the same object. You are creating two different objects (the two threads).




回答3:


The lock used by synchronized methods is associated with an instance of class MyThread. Since each thread has its own instance MyThread, each thread is synchronizing on its own lock.

If you wanted to synchronize across all threads, you could do something along the lines of:

public class MyThread extends Thread {

    private static final Object sharedLock = new Object();

    public void doSomething() {
      synchronized(sharedLock) {
        for(int i=0; i<100000; i++) {
          System.out.println(this.i);
        }
      }
    }
    ...
 }

An alternative is to synchronize on MyThread.class, but I prefer the first approach.

In the comments you say that if you change your code to use synchronized(this) in doSomething, all of a sudden it works. I am pretty sure it doesn't. It may have worked by chance, but it won't work repeatedly and reliably.



来源:https://stackoverflow.com/questions/8065333/threading-and-synchronized-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!