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는 항상 내가 읽은 the article과 반대 인 SecondThread보다 먼저 실행됩니다.왜 FirstThread는 다음 코드에서 SecondThread보다 먼저 실행됩니까?
이유 첫 번째 스레드가 두 번째 스레드보다 먼저 실행해야합니까? 그렇지 않다면 나에게 좋은 모범을 보여줄 수 있습니까? 감사.
실행 코드가 ABABABABAB을 제공합니다 ...... 121212121212하지만 예상대로 ABAB1212AB12AB12AB12A1B2 –
이 맞습니다. run() 메서드를 호출하면 일반적인 메서드를 호출하는 것처럼 호출되므로 그에 따라 작동하지만, 동시에 실행하려면 start() 메서드를 사용하여 호출해야합니다. 그러나 다른 기계에서 스레드의 동작은 다를 수 있습니다. – gprathour