【发布时间】:2021-10-19 02:08:00
【问题描述】:
根据 synchronized 关键字,如果应用于方法,则它会获取对象锁,并且具有相同实例的多个方法将无法同时执行这些方法。
但在下面的示例中,执行是同时发生的。 请看一下:-
public class ncuie extends Thread{
int b;
ncuie(int a){
b=a;
}
public synchronized void abc() throws InterruptedException {
for (int i = 0; i < 10; i++) {
System.out.println("thread 1 "+i);
}
}
public synchronized void pqr() throws InterruptedException {
for (int i = 0; i < 10; i++) {
System.out.println("thread 2 "+i);
}
}
public void run() {
try {
if(b==5) {
abc();
}
if(b==10) {
pqr();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
Thread t=new ncuie(5);
Thread t1=new ncuie(10);
t.start();
t1.start();
}
}
根据输出,有时执行线程 1,有时执行线程 2。 理想情况下,只有一个线程应该获得锁并完成它的执行,然后才应该启动第二个。
输出:-
thread 1 0
thread 1 1
thread 2 0
thread 2 1
thread 2 2
thread 1 2
thread 1 3
thread 1 4
thread 1 5
thread 1 6
thread 1 7
thread 1 8
thread 2 3
thread 2 4
thread 2 5
thread 2 6
thread 1 9
thread 2 7
thread 2 8
thread 2 9
【问题讨论】:
-
发生这种情况是因为您创建了类
ncuie的多个实例。锁是每个对象。第一个线程锁定一个对象,第二个线程锁定另一个对象。 -
那么我们应该如何创建多个具有相同实例的线程来实现正确的同步呢?
标签: java multithreading thread-safety synchronized java.util.concurrent