经典面试题:线程调度
-
题目要求: 启动两个线程, 一个输出 1,3,5,7…99, 另一个输出 2,4,6,8…100 最后 STDOUT 中按序输出 1,2,3,4,5…100
-
代码实现(感觉不是很完美)
public class ThreadScheduleExample implements Runnable {
private int start = 0;
public static void main(String[] args) {
ThreadScheduleExample obj = new ThreadScheduleExample();
Thread thread1 = new Thread(obj);
Thread thread2 = new Thread(obj);
thread1.start();
thread2.start();
}
@Override
public void run() {
while (start < 10) {
synchronized (this) {
this.notify();
System.out.println(Thread.currentThread().getName() + ": " + String.valueOf(start));
start += 1;
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}