为什么FirstThread总是在以下代码中的SecondThread之前运行?

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之前运行,这与我读过的文章相反。

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

使用start not run

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

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

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

“不仅机器的结果会有所不同,而且在同一台机器上多次运行相同的程序可能会产生不同的结果。永远不要假设一个线程会在另一个线程执行之前执行某些操作,除非您使用同步强制执行特定的操作执行顺序“

你不能指望线程在所有机器上以相同的方式运行。 这一切都取决于机器如何安排它们。