public class TestThreadInput {
public static void main(String[] args) {
RunnableImp runnableImp = new RunnableImp();
Thread t1 = new Thread(runnableImp, “奇数线程”);
Thread t2 = new Thread(runnableImp, “偶数线程”);
t1.start();
t2.start();
}
}
class RunnableImp implements Runnable {
private static int i;
@Override
public synchronized void run() {
while (i < 10) {
i++;
if (i % 2 != 0) {
notifyAll();//唤醒所有线程,线程1进入
System.out.println(Thread.currentThread().getName() + "=" + i);
try {
wait();//线程1挂起,等待唤醒
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
notifyAll();//唤醒所有线程,线程2进入
System.out.println(Thread.currentThread().getName() + "=" + i);
try {
wait();//线程2挂起,等待唤醒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}