java多线程的应用-使用两个线程打印12A34B56C78D
public class Test03 {
public static void main(String[] args) {
//1.创建共用的对象
Outer outer = new Outer();
//2.创建数字线程和字母线程
Thread chThread = new Thread(new CharRunable(outer));
//3.启动
chThread.start();
Thread numThread = new Thread(new NumberRunable(outer));
numThread.start();
}
}
/**
* 数字线程
*/
class NumberRunable implements Runnable {
private Outer outer;
public NumberRunable(Outer outer) {
this.outer = outer;
}
@Override
public void run() {
synchronized (outer) {
while (outer.num <= 52) {
if (outer.flag) {
System.out.print(outer.num++);
if (outer.num % 2 == 1) {
outer.flag = false;
outer.notifyAll();
}
} else {
try {
outer.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
//字母线程
class CharRunable implements Runnable {
private Outer outer;
public CharRunable(Outer outer) {
this.outer = outer;
}
@Override
public void run() {
synchronized (outer) {
while (outer.ch <= 'Z') {
if (!outer.flag) {
System.out.print(outer.ch++);
outer.flag = true;
outer.notifyAll();
} else {
try {
outer.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
//创建共用的对象
class Outer {
public int num = 1;
public char ch = 'A';
public boolean flag = true; //表示数字线程先打印
}