私は2つのスレッドを使用しようとしています。1つのスレッドは奇数のみを印刷し、もう1つのスレッドは偶数のみを印刷し、代替操作でなければなりません。
例えば:
Thread1 1
Thread2 2
Thread1 3
Thread2 4
and so on..
以下はプログラムです。スレッド2が通知している場合でも、スレッド1が待機状態から抜け出さないため、どこが間違っているか教えてください..
public class ThreadInteraction {
public static void main(String[] args) {
new ThreadInteraction().test();
}
private void test() {
ThreadA ta = new ThreadA();
Thread t = new Thread(ta);
t.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
for(int i=2;i<=50;){
System.out.println("Thread2 "+i);
synchronized (t) {
try {
t.notify();
t.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
i=i+2;
}
}
}
class ThreadA implements Runnable{
@Override
public void run() {
for(int i=1;i<50;){
System.out.println("Thread1 "+i);
synchronized (this) {
try {
notify();
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
i=i+2;
}
}
}