gpt4 book ai didi

java - 为什么下面给出的程序会得到不同的输出?

转载 作者:行者123 更新时间:2023-12-01 10:59:14 24 4
gpt4 key购买 nike

对于此代码,线程 t1 的数字从 1 到 10 打印,之后线程 t2 的数字打印。

class Synchtest {
public static void main(String args[]) {
synchtest2 a = new synchtest2();
Thread t1 = new Thread(a);
Thread t2 = new Thread(a);
t1.start();
t2.start();
}
}

class synchtest2 extends Thread {

public synchronized void run() {
for (int i = 0; i <= 10; i++) {
System.out.println(i);
try {
sleep(1000);
} catch (Exception e) {
}
}
}
}

但是对于下面的代码,他们打印为 00 11 22 33 44 55 等等。

class Synchtest {
public static void main(String args[]) {

synchtest2 t = new synchtest2();
synchtest2 t2 = new synchtest2();
t.start();
t2.start();
}
}

class synchtest2 extends Thread {

public synchronized void run() {
for (int i = 0; i <= 10; i++) {
System.out.println(i);
try {
sleep(1000);
} catch (Exception e) {

}

}
}
}

最佳答案

在第一个示例中,两个线程都使用单个synchtest2实例作为它们的Runnable,并且它的run()方法是同步的。因此,启动的第一个线程获取这个唯一实例的监视器,打印所有数字,然后释放监视器,允许第二个线程运行。

在第二个示例中,您有两个不同的实例,每个线程都使用自己的实例。因此,它们都并行获取自己的监视器(因为每个对象都有自己的监视器),并愉快地同时打印它们的数字。

关于java - 为什么下面给出的程序会得到不同的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33453009/

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