Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

java - why Synchronized method allowing multiple thread to run concurrently?

I have following program in same file. I have synchronized the run() method.

class MyThread2 implements Runnable {
    Thread    t;

    MyThread2(String s) {
        t=new Thread(this,s);
        t.start();
    } 

    public synchronized  void  run() {
        for (int i=0;i<3;i++) {
            System.out.println("Thread name : "+ Thread.currentThread).getName());
            try {
                t.sleep(1000);
            }
            catch (InterruptedException e) {
                e.getMessage();
            }
        }
    }
}

class TestSync {
    public static void main(String[] args) {
        MyThread2 m1=new MyThread2("My Thread 1");
        c.fun();
    }
}

class c {
    static void fun() {
        MyThread2 m1=new MyThread2("My Thread 4");
    }
}

output is

Thread name : My Thread 1
Thread name : My Thread 4
Thread name : My Thread 4
Thread name : My Thread 1
Thread name : My Thread 1
Thread name : My Thread 4

My question is why is synchronized method allowing both "My Thread 1" and "My Thread 4" thread access concurrently?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

synchronized methods work at the instance level. Each instance of the class gets its own lock. The lock gets acquired every time any synchronized method of the instance is entered. This prevents multiple threads calling synchronized methods on the same instance (note that this also prevents different synchronized methods from getting called on the same instance).

Now, since you have two instances of your class, each instance gets its own lock. There's nothing to prevent the two threads each operating on its own instance concurrently.

If you do want to prevent this, you could have a synchronized(obj) block inside run(), where obj would be some object shared by both instances of your class:

class MyThread2 implements Runnable {
   private static final Object lock = new Object();
   ...
   public void run() {
     synchronized(lock) {
       ...
     }
   }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...