public class PrintTwo {
public static void main(String[] args) {
Print print = new Print();
IntThread intThread = new IntThread(print);
LetterThread letterThread = new LetterThread(print);
intThread.start();
letterThread.start();
}
}
class IntThread extends Thread {
private Print print;
public IntThread(Print print) {
this.print = print;
}
@Override
public void run() {
print.printInt();
}
}
class LetterThread extends Thread {
private Print print;
public LetterThread(Print print) {
this.print = print;
}
@Override
public void run() {
print.printLetter();
}
}
class Print {
private boolean flag = true;
public synchronized void printInt() {
int i = 1;
while (i < 53) {
if (!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.print(i);
i++;
if ((i - 1) % 2 == 0) {
flag = false;
notify();
}
}
}
}
public synchronized void printLetter() {
char i = 'A';
while (i <= 'Z') {
if (flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.print(i);
i++;
flag = true;
notify();
}
}
}
}
class Test {
public static void main(String[] args) {
Park pk = new Park();
Thread t1 = new Thread(new CarInThread(pk));
Thread t2 = new Thread(new CarOutThread(pk));
t1.start();
t2.start();
}
}
public class Park {
private int states = 3;
public synchronized void carIn(int i) {
if (states == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.println(i + "号车已停车!");
System.out.println("还剩" + --states + "个车位");
notifyAll();
}
}
public synchronized void carOut(int i) {
if (states == 3) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.println(i + "号车已经驶离!");
System.out.println("还剩" + (++states) + "个车位");
notifyAll();
}
}
}
class CarInThread implements Runnable {
Park pk;
public CarInThread(Park pk) {
this.pk = pk;
}
@Override
public void run() {
for (int i = 1; i <= 20; i++) {
pk.carIn(i);
}
}
}
class CarOutThread implements Runnable {
Park pk;
public CarOutThread(Park pk) {
this.pk = pk;
}
@Override
public void run() {
for (int i = 1; i <= 20; i++) {
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
pk.carOut(i);
}
}
}