实例变量同步

Sam*_*eer 2 java multithreading thread-synchronization

在下面的示例中,锁定是在实例变量employee上获得的(不在此),但在进入synchronized块时,TestClass1的Threads仍然被锁定.任何建议为什么这种行为.据我所知,如果它同步就应该被锁定.

public class TestClass{
  public static void main(String args[]){
    TestClass1 obj = new TestClass1();
    Thread t1 = new Thread(obj, "T1");
    Thread t2 = new Thread(obj, "T2");
    t1.start();
    t2.start();
  }
}

class TestClass1 implements Runnable{

Employee employee = new Employee();

public void myMethod () {
    synchronized (employee) {
        try {
            Thread.sleep(4000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public void myOtherMethod() {
    synchronized (employee) {
        try {
            Thread.sleep(4000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

@Override
public void run() {
    myMethod();
    myOtherMethod();
}
}
Run Code Online (Sandbox Code Playgroud)

Kep*_*pil 5

TestClass1对两个线程使用相同的实例,因此它们使用相同的Employee实例来锁定.

要让他们使用不同的锁,您需要:

Thread t1 = new Thread(new TestClass1(), "T1");
Thread t2 = new Thread(new TestClass1(), "T2");
Run Code Online (Sandbox Code Playgroud)