Jic*_*hao 2 java multithreading
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();
}
}
Run Code Online (Sandbox Code Playgroud)
输出显示FirstThread始终在SecondThread之前运行,这与我读过的文章相反.
为什么?第一个线程必须在第二个线程之前运行吗?如果没有,你能告诉我一个很好的例子吗?谢谢.
使用start not run
public static void main(String[] args) {
new FirstThread().start();
new SecondThread().start();
}
Run Code Online (Sandbox Code Playgroud)
如果使用run方法,则调用第一个方法,然后调用第二个方法.如果要运行并行线程,则必须使用线程的start方法.