public class OddAndEven {
//唤醒和等待,同时锁住,会形成交替效果
public synchronized void print(String str){
notify();
System.out.println(str);
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//运行多线程
public static void main(String[] args) {
OddAndEven oe = new OddAndEven();
new Thread(oe.new Odd()).start();
new Thread(oe.new Even()).start();
}
//偶数
class Odd implements Runnable{
@Override
public void run() {
for (int i = 0; i <=100 ; i+=2) {
print(i+"");
}
}
}
//奇数
class Even implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 100; i += 2) {
print(i+"");
}
}
}
}