目标:Number线程类执行数字的递增并输出,并且没增加两个就切换到另外一个线程,Letter线程类执行字母的递增并输出,并且没输出一个就切换到另外一个线程。
主类:
public static void main(String[] args) {
Print print = new Print();
Number number = new Number(print);
Letter letter = new Letter(print);
Thread thread = new Thread(number);
Thread thread2 = new Thread(letter);
thread.start();
thread2.start();
}
数字类:
private Print print;
/**
* 带参数的构造方法传入 print对象 确保两个线程类操作的是同一个对象
*
* @param print
*/
public Number(Print print) {
super();
this.print = print;
}
@Override
public void run() {
if (print.getTemp()) {//如果符合条件就往下执行
synchronized (print) {//该对象获得锁
for (int i = 1; i <= 52; i++) {
System.out.println(i);
if (i % 2 == 0) {
try {
print.setTemp(false);//首先把标志更改
print.notifyAll();//唤醒其他所有正在等待的线程
print.wait();//并把此线程处于等待状态
print.notify();//唤醒此线程,防止程序执行到最后仍处于未停止状态
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
}
}
字母类:
private Print print;
public Letter(Print print) {
super();
this.print = print;
}
@Override
public void run() {
if (!print.getTemp()) {
synchronized (print) {
for (int i = 65; i <= 90; i++) {
System.out.println((char) i);
try {
print.setTemp(true);
print.notifyAll();
print.wait();
print.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
标识类:
private boolean temp = true;
public boolean getTemp() {
return temp;
}
public void setTemp(boolean temp) {
this.temp = temp;
}