为什么FirstThread总是在以下代码中的SecondThread之前运行? [英] Why does the FirstThread always run before the SecondThread in the following code?
本文介绍了为什么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之前运行这与我读过的文章相反。
The output shows that the FirstThread always runs before the SecondThread which is opposite from the article I read.
为什么?第一个线程必须在第二个线程之前运行吗?如果没有,你能告诉我一个很好的例子吗?谢谢。
Why?Must the first thread run before the second thread? If not, could you show me a good example? Thanks.
推荐答案
使用开始不运行
public static void main(String[] args) {
new FirstThread().start();
new SecondThread().start();
}
如果使用run方法,则调用第一个方法,然后调用第二个方法。如果要运行并行线程,则必须使用线程的start方法。
If you use run method, you call first method and after second method. If you want to run parallel threads, you must use start method of thread.
这篇关于为什么FirstThread总是在以下代码中的SecondThread之前运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文