gpt4 book ai didi

java - Java中同步10个线程

转载 作者:行者123 更新时间:2023-12-02 05:18:35 25 4
gpt4 key购买 nike

为什么我会得到

22291 3091 0 351 0 1423 0 0 0 0

而不是

0 0 0 0 0 0 0 0 0 0

当我在 Java 中运行此代码时:

import java.lang.Thread;

class MainThread {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) new MyThread().start();
}
}

class MyThread extends Thread {
static int counter = 0;
static Object mutex = new Object();
public void run() {
synchronized (mutex) {
for (int i = 0; i < 1000000; i++) counter = counter + 1;
for (int i = 0; i < 1000000; i++) counter = counter - 1;
}
System.out.print(counter + " ");
}
}

最佳答案

您得到该输出是因为 print 语句未同步。 线程完成两个 for 循环并存在于 syncronized block 后,计数器 = 0
但在打印出 counter 之前,其他一些线程会进入 syncronized block 并开始递增 counter
这就是为什么前面的线程打印递增的计数器

public void run() {
synchronized (mutex) {
for (int i = 0; i < 1000000; i++) counter = counter + 1;
for (int i = 0; i < 1000000; i++) counter = counter - 1;
}
// Here the current thread exited the sync block and some other thread get into this block
// and started incrementing the counter

System.out.print(counter + " "); // your thread prints incremented counter
}

关于java - Java中同步10个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26693707/

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