多线程并发操作,停车以及出车库过程模拟,多个线程通信过程。
package test;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
boolean[] p = new boolean[3];
for (int i = 0; i < 3; i++) {
p[i] = false;
}
Park pa = new Park(p);
new Tpark("小明", pa).start();
new Tpark("小张", pa).start();
new Tpark("小红", pa).start();
new Tpark("小李", pa).start();
new C_park(2, pa).start();
}
}
class Park {
public boolean[] p = new boolean[3];
public int PP = 0;
public Park() {
};
public Park(boolean[] p) {
this.p = p;
};
}
class Tpark extends Thread { //停车
private Park p;
private boolean flag = true; //用来标志是否已经停车
public Tpark() {
}
public Tpark(String name, Park p) {
super(name);
this.p = p;
}
public void run() {
synchronized (p) {
while (flag) {
if (p.PP < 3) {
int x = 0;
for (int i = 0; i < 3; i++) {
if (p.p[i] == false) {
p.p[i] = true;
System.out.println(Thread.currentThread().getName() + "停入" + (i + 1) + "号车库");
flag = false;
break;
}
}
for (int i = 0; i < 3; i++) {
if (p.p[i] == true) {
x++;
}
}
p.PP = x;
} else {
System.out.println("抱歉," + Thread.currentThread().getName() + " 先生(女士),停车位目前已满,请您稍作等待!!!");
try {
p.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
class C_park extends Thread { //出库
private Park p;
private int no;
public C_park() {
}
public C_park(int no, Park p) {
this.no = no;
this.p = p;
}
public void run() {
synchronized (p) {
p.p[no - 1] = false;
p.PP--;
System.out.println(no + "号车位已空闲");
p.notifyAll();
}
}
}
运行结果:
小明停入1号车库
小李停入2号车库
小红停入3号车库
抱歉,小张 先生(女士),停车位目前已满,请您稍作等待!!!
2号车位已空闲
小张停入2号车库