/**
* java 2个线程交替打印奇偶数
* @author Administrator
*
*/
public class Main {
public static void main(String[] args) {
Print p=new Print();
Thread a=new Thread(p,"A");//A打印偶数
Thread b=new Thread(p,"B");//B打印奇数
a.start();
b.start();
}
}
class Print implements Runnable{
@Override
public synchronized void run() {
try {
for(int i=0;i<10;i++) {
if(i%2==0) {
if(Thread.currentThread().getName().equals("A")) {
System.out.println("A:"+i);
this.wait();
}
}else {
if(Thread.currentThread().getName().equals("B")) {
System.out.println("B:"+i);
this.wait();
}
}
this.notify();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
A:0
B:1
A:2
B:3
A:4
B:5
A:6
B:7
A:8
B:9