java 为什么同步方法允许多个线程并发运行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7659615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
why Synchronized method allowing multiple thread to run concurrently?
提问by user980089
I have following program in same file. I have synchronized the run() method.
我在同一个文件中有以下程序。我已经同步了 run() 方法。
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?
我的问题是为什么同步方法允许同时访问“My Thread 1”和“My Thread 4”线程?
回答by NPE
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 differentsynchronized
methods from getting called on the same instance).
synchronized
方法在实例级别工作。类的每个实例都有自己的锁。每次synchronized
输入实例的任何方法时都会获取锁。这可以防止多个线程在同一实例上调用synchronized
方法(请注意,这也可以防止在同一实例上调用不同的方法)。synchronized
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:
如果你确实想防止这种情况发生,你可以在synchronized(obj)
里面有一个块run()
,obj
你的类的两个实例共享一些对象:
class MyThread2 implements Runnable {
private static final Object lock = new Object();
...
public void run() {
synchronized(lock) {
...
}
}
}