<分区>
我正在学习多线程并想编写一些具有竞争条件的代码。但是这些代码不起作用:我已经多次运行代码,但它总是打印 10,这是没有竞争条件的正确结果。有人可以告诉为什么吗?谢谢。
这是主要功能。它会创建10个线程来修改一个静态变量,并在最后打印这个变量。
public static void main(String[] args) {
int threadNum = 10;
Thread[] threads = new Thread[threadNum];
for (int i = 0; i < threadNum; i++) {
threads[i] = new Thread(new Foo());
}
for (Thread thread : threads) {
thread.run();
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
}
}
// will always print 10
System.out.println(Foo.count);
}
下面是 Foo 的定义:
class Foo implements Runnable {
static int count;
static Random rand = new Random();
void fn() {
int x = Foo.count;
try {
Thread.sleep(rand.nextInt(100));
} catch (InterruptedException e) {
}
Foo.count = x + 1;
}
@Override
public void run() {
fn();
}
}