gpt4 book ai didi

java - 共享计数器和 Java 线程

转载 作者:行者123 更新时间:2023-11-29 04:48:24 25 4
gpt4 key购买 nike

我正在检查一个示例并对其进行测试,每次运行都会得到不同的输出。这是代码:

    public class Th1 implements Runnable{
private int i=0;
public void run(){
try{
Thread.sleep(1000);
} catch (InterruptedException ex){
}
while(i<10){
System.out.println(i);
i+=1;
} }

public static void main(String[] args) {
Th1 t = new Th1();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
t2.start();
}

这是第一次运行的输出

    0
1
2
3
4
5
6
7
8
9
0

第二次运行输出:

    0
1
2
3
4
5
6
7
8
9

据我所知,第一个输出的解释是每个线程都有自己的缓存,第二个线程最后启动,打印它是 i (0),当它检查内存以增量编辑 i 时,它发现实际值为 10,因此变为 11,并退出循环。但为什么第二轮只有一个零??

最佳答案

除了@Gunner@mel3kings实际上线程彼此并行运行,操作系统可能允许一个线程有更多时间而不是下一个线程。

场景一;

   loop     Thread1              Thread2
t1 sleep sleep
t2 started to loop started the loop
t4 print 0 print 1
t5 print 2 print 3
t6 print 4 print 5
t7 print 6 print 7
t8 print 8 print 9
t9 print 10 exit to loop

场景 2

   loop       Thread1              Thread2
t1 sleep sleep
t2 started to loop
t4 print 0
t5 print 1
t6 print 2
t7 print 3
t8 print 4 started loop
t9 ..................................

场景三(也可能)

   loop       Thread1              Thread2
t1 sleep sleep
t2 started to loop started loop
t3 print 0 send i to print
t4 print 1
t5 print 2
t6 print 3
t7 print 4
t8 print 5
t9 print 6
t10 print 7
t11 print 8
t12 print 9
t13 exit print 0 (delay of console output may cause that)

还有其他输出场景。

无论如何要查看其详细信息,请尝试使用以下带有线程名称的代码并查看哪个线程打印每个输出

public class Th1 implements Runnable {
private int i = 0;

public void run() {
String name = Thread.currentThread().getName();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
while (i < 10) {
System.out.println(name + ": " + i);
i += 1;
}
}

public static void main(String[] args) {
Th1 t = new Th1();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
t2.start();

}
}

输出

Thread-1: 0
Thread-1: 1
Thread-1: 2
Thread-0: 0 //last zero may comes from here but print order is about console
Thread-1: 3
Thread-1: 4
Thread-1: 5
Thread-1: 6
Thread-1: 7
Thread-1: 8
Thread-1: 9

关于java - 共享计数器和 Java 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36329079/

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