两个线程交替输出1-26和A-Z

public class 交替输出 {
【两个线程交替输出1-26和A-Z】public static void main(String[] args) throws InterruptedException {
Num num = new Num(1,'A');

Thread t1 = new Thread(new Odd(num));
t1.setName("t1");
Thread t2 = new Thread(new Even(num));
t2.setName("t2");

t1.start();

Thread.sleep(1000);

t2.start();
}
}
//共享数据
class Num{
int count; //输出数字
char c; //输出字符
public Num(int count,char c) {
super();
this.count = count;
this.c = c;
}

//打印奇数
public synchronized void printOdd() throws InterruptedException {
System.out.println(Thread.currentThread().getName() +"-->" +(count++));
this.notifyAll();
this.wait(); //t1线程无期限的等待
Thread.sleep(1000);
}
//打印偶数
public synchronized void printEven() throws InterruptedException {
System.out.println(Thread.currentThread().getName() +"-->" +(c++));
this.notifyAll();
this.wait(); //t2线程无期限的等待
Thread.sleep(1000);
}
}
//线程1
class Odd implements Runnable{
Num num;
public Odd(Num num) {
super();
this.num = num;
}
public void run() {
while (true) {
//打印奇数
try {
num.printOdd();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}
//线程2
class Even implements Runnable{
Num num;
public Even(Num num) {
super();
this.num = num;
}
public void run() {
while (true) {
//打印偶数
try {
num.printEven();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}

    推荐阅读