나는 두 개의 스레드 T1 시작 1,3,5, ..... 및 스레드 두 개의 T2 인쇄 2,4,6 .... 아래 코드를 시작합니다.스레드 실행을 예측할 수 없습니다
public class T1T2Print {
public static void main(String[] args) {
Counter c = new Counter();
c.count = 1;
printThread t1 = new printThread(c);
Thread T1 = new Thread(t1);
T1.setName("T1");
printThread t2 = new printThread(c);
Thread T2 = new Thread(t2);
T2.setName("T2");
T2.start();
T1.start();
}
}
class printThread implements Runnable {
public Counter count;
public int reminder;
public printThread(Counter count) {
this.count = count;
}
public void run() {
for (int i = 1; i <= 5; i++) {
synchronized (count) {
String name = Thread.currentThread().getName();
if (count.count % 2 != 0 && !name.equals("T1")) {
try {
count.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.println(name + " :: " + count.count);
count.count++;
count.notify();
}
if (count.count % 2 == 0 && !name.equals("T2")) {
try {
count.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.println(name + " :: " + count.count);
count.count++;
count.notify();
}
}
}
}
}
출력은 다음과 같습니다 :
T1 :: 1
T2 :: 2
T1 :: 3
T2 :: 4
T1 :: 5
T2 :: 6
T1 :: 7
T2 :: 8
T1 :: 9
T2 :: 10
하지만 난
T1.start();
T2.start();
다음과 같이 출력 변경, 왜이 문제
에 스레드를 시작하는 순서를 변경하는 경우T1 :: 1
T2 :: 2
T2 :: 3
T2 :: 4
T2 :: 5
T2 :: 6
T2 :: 7
T2 :: 8
T2 :: 9
T2 :: 10
T2 :: 11
T1 :: 12
T1 :: 13
T1 :: 14
T1 :: 15
T1 :: 16
T1 :: 17
T1 :: 18
T1 :: 19
내 생각 엔 당신이 여기 세부에서 분명하지 않다 뭔가를 잘못하고있는 것입니다. 'wait()'를 호출하면 그렇게해야합니다. 기다리고 있음을 보여주기 위해 print 문을 추가합니다. –