gpt4 book ai didi

java - 为什么这些线程不按顺序运行?

转载 作者:行者123 更新时间:2023-11-30 08:48:18 24 4
gpt4 key购买 nike

<分区>

我很难理解synchronized 和可重入锁。这是我正在试验的小程序:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Reentr {

public static void main(String[] args) {
ExecutorService eService = Executors.newFixedThreadPool(2);
for (int i = 1; i <= 2; i++) {
eService.execute(new process());
}

try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

eService.shutdown();
}

}

class process implements Runnable {
int count = 0;

@Override
public void run() {

processTest();
}

public synchronized void processTest() {
try {
for (int i = 1; i <= 2; i++) {
count += i;
System.out.println("count value for " + Thread.currentThread().getName() + " is " + count);
}
} finally {
System.out.println("count for " + Thread.currentThread().getName() + " is " + count);
}
}

}

输出是:

count value for pool-1-thread-2 is 1
count value for pool-1-thread-1 is 1
count value for pool-1-thread-2 is 3
count for pool-1-thread-2 is 3
count value for pool-1-thread-1 is 3
count for pool-1-thread-1 is 3

如果我们在输出中看到两个线程在同步块(synchronized block)中。我的印象是一个线程必须完成同步方法的执行,之后另一个线程才会进入该方法。

理想情况下,我期待这样的结果

count value for pool-1-thread-1 is 1
count value for pool-1-thread-1 is 3
count for pool-1-thread-1 is 3
count value for pool-1-thread-2 is 1
count value for pool-1-thread-2 is 3
count for pool-1-thread-2 is 3

我已经用同步块(synchronized block)和可重入锁替换了同步方法。但是,我仍然有相同的输出。我错过了什么?

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