/**
*
*/
package Synchronized;
/**
* @author libin
*
*/
public class CarTest {
public static void main(String[] args) {
CarSet car1 = new CarSet();
Thread t1 = new InThread("1",car1);
Thread t2 = new InThread("2",car1);
Thread t3 = new InThread("3",car1);
Thread t4 = new OutThread("4",car1);
Thread t5 = new OutThread("5",car1);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
class InThread extends Thread //入库线程
{
String name;
CarSet car;
public InThread(){}
public InThread(String name,CarSet car)
{
super(name);
this.car = car;
}
public void run()
{
car.CarIn();
}
}
class OutThread extends Thread
{
String name;
CarSet carSet;
public OutThread(){}
public OutThread(String name,CarSet carSet)
{
super(name);
this.carSet = carSet;
}
public void run()
{
carSet.CarOut();
}
}
class CarSet
{
//String carName;
private boolean[] place = new boolean[3];
public CarSet(){}
// public CarSet(String carSetName)
// {
// this.carName = carSetName;
// }
public synchronized void CarIn()
{
try
{
if(place[0]&&place[1]&&place[2])
{
System.out.println("车位已满,请等待。");
wait();
}
for(int i = 0; i < 3; i++)
{
if(place[i] == false)//车位空,可以入库
{
System.out.println(Thread.currentThread().getName()+"可以入"+i+"号库");
place[i] = true;
notifyAll();
break;
}
}
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
public synchronized void CarOut()
{
try
{
if(!(place[0]||place[1]||place[2]))
{
wait();
}
for(int i = 0; i < 3; i++)
{
if(place[i] == true)//车在库内,可以出库
{
System.out.println(Thread.currentThread().getName()+"可以从"+i+"号库出库");
place[i] = false;
notifyAll();
break;
}
}
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}