gpt4 book ai didi

java - 为什么同步在第二个代码中不起作用?

转载 作者:搜寻专家 更新时间:2023-10-31 08:22:06 25 4
gpt4 key购买 nike

同步在此代码中正常工作:

    class PrintNumbers {
synchronized public void display() {
System.out.println("in display");
for (int i = 0; i < 3; i++) {
System.out.println("Thread name : "+ Thread.currentThread().getName() + " i= " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.getMessage();
}
}
System.out.println("out of display");
}
}

class MyThread implements Runnable {
Thread t;
PrintNumbers printNumbers;

MyThread(PrintNumbers printNumbers, String s) {
this.printNumbers = printNumbers;
t = new Thread(this,s);
t.start();
}

public void run() {
printNumbers.display();
}
}

class SyncExample {
public static void main(String[] args) {
PrintNumbers printNumbers = new PrintNumbers();

new MyThread(printNumbers, "My Thread 1");
new MyThread(printNumbers, "My Thread 2");
}
}

输出:

in display  
Thread name : My Thread 1 i= 0
Thread name : My Thread 1 i= 1
Thread name : My Thread 1 i= 2
out of display
in display
Thread name : My Thread 2 i= 0
Thread name : My Thread 2 i= 1
Thread name : My Thread 2 i= 2
out of display

但不在这段代码中:

    class PrintNumbers {
synchronized public void display() {
System.out.println("in display");
for (int i = 0; i < 3; i++) {
System.out.println("Thread name : "+ Thread.currentThread().getName() + " i= " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.getMessage();
}
}
System.out.println("out of display");
}
}

class MyThread implements Runnable {
Thread t;
PrintNumbers printNumbers;

MyThread(String s) {
this.printNumbers = new PrintNumbers();
t = new Thread(this,s);
t.start();
}

public void run() {
printNumbers.display();
}
}

class SyncExample {
public static void main(String[] args) {
new MyThread("My Thread 1");
new MyThread("My Thread 2");
}
}

输出:

in display  
Thread name : My Thread 1 i= 0
in display
Thread name : My Thread 2 i= 0
Thread name : My Thread 1 i= 1
Thread name : My Thread 2 i= 1
Thread name : My Thread 2 i= 2
Thread name : My Thread 1 i= 2
out of display
out of display

我无法理解在 Runnable MyThread 和 SyncExample 类中初始化 PrintNumbers 与 Synchronization 有什么区别。请解释。

最佳答案

I cannot understand what difference wrt Synchronization does it make to initialize PrintNumbers in the Runnable MyThread and in the SyncExample class.

事实并非如此。 重要的是,在您的第一个示例中,您只有两个线程共享的 one PrintNumbers 实例。但在第二个示例中,您有两个单独的 PrintNumbers 实例,每个线程一个。

由于 PrintNumbers#display 在实例上同步(synchronized 实例方法在 this 上同步),它只在实例内同步,而不是跨实例同步多个实例。

当两个线程共享一个实例时,对 display 的两次调用被序列化。但是当每个线程都有自己的实例时,对 display 的两次调用是在不同的实例上进行的,因此调用没有序列化,它们可以重叠。

关于java - 为什么同步在第二个代码中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39930641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com