This question already has answers here:
What's the difference between Thread start() and Runnable run()

(15个回答)


5年前关闭。




我正在学习多线程,并想编写一些具有竞争条件的代码。但是这些代码不起作用:我已经运行了很多次代码,但是它始终会打印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会调用run方法,并且不会启动任何线程。请使用thread.start来启动线程。

09-07 03:14