【问题标题】:Why does the FirstThread always run before the SecondThread in the following code?为什么在下面的代码中 FirstThread 总是在 SecondThread 之前运行?
【发布时间】:2011-11-24 14:22:17
【问题描述】:
public class TowThreads {
    public static class FirstThread extends Thread {
        public void run() {
            for (int i = 2; i < 100000; i++) {
                if (isPrime(i)) {
                    System.out.println("A");
                    System.out.println("B");
                }
            }
        }

        private boolean isPrime(int i) {
            for (int j = 2; j < i; j++) {
                if (i % j == 0)
                    return false;
            }
            return true;
        }
    }

    public static class SecondThread extends Thread {
        public void run() {
            for (int j = 2; j < 100000; j++) {
                if (isPrime(j)) {
                    System.out.println("1");
                    System.out.println("2");
                }
            }
        }

        private boolean isPrime(int i) {
            for (int j = 2; j < i; j++) {
                if (i % j == 0)
                    return false;
            }
            return true;
        }
    }

    public static void main(String[] args) {
        new FirstThread().run();
        new SecondThread().run();
    }
}

输出显示 FirstThread 总是在 SecondThread 之前运行,这与我阅读的 the article 相反。

为什么?第一个线程必须在第二个线程之前运行?如果没有,你能给我举一个很好的例子吗?谢谢。

【问题讨论】:

    标签: java multithreading


    【解决方案1】:

    使用启动不运行

    public static void main(String[] args) {
            new FirstThread().start();
            new SecondThread().start();
        }
    

    如果你使用 run 方法,你调用第一个方法和第二个方法之后。如果要运行并行线程,则必须使用线程的 start 方法。

    【讨论】:

      【解决方案2】:

      这取决于机器处理器和 jvm 他们如何安排你的线程。即使在你读过的文章中也明确提到过

      “不仅结果可能因机器而异,而且在同一台机器上多次运行同一个程序可能会产生不同的结果。永远不要假设一个线程会在另一个线程之前做某事,除非你已经使用同步来强制执行特定的顺序"

      您不能期望线程在所有机器上都以相同的方式运行。这完全取决于机器如何安排它们。

      【讨论】:

      • 我认为运行代码给出 ABABABABAB......121212121212 但预期是 ABAB1212AB12AB12AB12A1B2
      • 你是对的。调用 run() 方法可以像调用普通方法一样调用,因此可以相应地工作,但是如果我们想同时运行它们,那么我们需要使用 start() 方法调用。但不同机器上的线程行为仍然可能不同。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-25
      • 2019-01-24
      • 2016-11-18
      • 1970-01-01
      • 2021-11-21
      • 1970-01-01
      相关资源
      最近更新 更多