【问题标题】:Why there's no race condition in this java program [duplicate]为什么这个java程序中没有竞争条件[重复]
【发布时间】: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


【解决方案1】:

因为您的程序中没有线程,幸运的是顺序程序没有竞争问题。你调用thread.run 调用run 方法并且不启动任何线程。请改用thread.start 来启动线程。

【讨论】:

  • 谢谢!在我使用thread.start 后它可以工作。