为什么Synchronized方法允许多个线程同时运行?
我在同一个文件中有以下程序。我已经同步了 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");
}
}
输出是
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
我的问题是为什么同步方法允许同时访问“我的线程 1”和“我的线程 4”线程?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
同步
方法在实例级别工作。类的每个实例都有自己的锁。每次进入实例的任何同步方法时都会获取锁。这可以防止多个线程在同一个实例上调用synchronized
方法(请注意,这也可以防止不同synchronized
方法获取在同一个实例上调用)。现在,由于您的类有两个实例,因此每个实例都有自己的锁。没有什么可以阻止两个线程同时在自己的实例上操作。
如果您确实想防止这种情况发生,可以在 run() 内添加一个 Synchronized(obj) 块,其中 obj 是共享的某个对象通过你的班级的两个实例:
synchronized
methods work at the instance level. Each instance of the class gets its own lock. The lock gets acquired every time anysynchronized
method of the instance is entered. This prevents multiple threads callingsynchronized
methods on the same instance (note that this also prevents differentsynchronized
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 insiderun()
, whereobj
would be some object shared by both instances of your class: