Why is there a synchronized method that allows multiple threads to start at the same time?

I have the following program in the same file. I 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

 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 does the synchronized method allow the simultaneous access of the threads "My Thread 1" and "My Thread 4"?

+7
source share
1 answer

synchronized operate at the instance level. Each instance of the class gets its own lock. A lock is acquired every time any synchronized instance method is introduced. This prevents multiple threads from invoking the synchronized methods in the same instance (note that this also prevents the various synchronized methods from being called in the same instance).

Now, since you have two instances of your class, each instance gets its own lock. There is nothing that would prevent two threads from working in their instance at the same time.

If you want to prevent this, you can have a synchronized(obj) block inside run() , where obj will 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) { ... } } } 
+27
source

All Articles