【发布时间】:2016-05-28 00:39:49
【问题描述】:
我正在学习多线程并想编写一些具有竞争条件的代码。但是这些代码不起作用:我已经运行了很多次代码,但它总是打印 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();
}
}
【问题讨论】:
-
thread.run();将此更改为thread.start() -
其他副本(如果有人希望更改当前副本,因为它可能过于笼统):*.com/q/8258536*.com/q/20323697
标签: java multithreading