用两个线程 输出 打印结果如 12A34B56C........52Z (唤醒)
final MyThread mt = new MyThread();
// 创建线程并在run()方法中调用print1()
new Thread() {
public void run() {
try {
mt.print1();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
// //创建线程并在run()方法中调用print1()
new Thread() {
public void run() {
try {
mt.print2();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
}
class MyThread {
// 定义静态变量
private static int sum = 1;
private static char c = 'A';
private static int flag = 1;
public void print1() throws InterruptedException {
// 创建循环
while (sum <= 52) {
// 创建锁
synchronized (this) {
// 定义线程间的通信
if (flag != 1)
this.wait();
// 内部循环每次调通该方法输出两次
for (int i = 1; i <= 2; i++) {
System.out.print(sum);
sum++;
}
flag = 2;
this.notify();
}
}
}
public void print2() throws InterruptedException {
// 创键循环
while (c <= 'Z') {
// 创建锁
synchronized (this) {
// 创建线程间的通信
if (flag != 2)
this.wait();
System.out.print(c);
c = (char) (c + 1);
flag = 1;
this.notify();
}
}
}
} |
|