/*线程同步示例,十字交通路口*/
import javax.swing.*;
import java.awt.*;
class Road extends JFrame {
ICar LRcar,TBcar;//声明小车对象
TrafficCop tCop;
Road()
{
setSize(400,400);
setVisible(true);
setTitle("线程同步示例");
setDefaultCloseOperation(EXIT_ON_CLOSE);//设置窗体关闭按钮的关闭动作
tCop = new TrafficCop();//创建交通警察(线程同步)对象
LRcar = new ICar(tCop,ICar.leftToRight,16);//创建从左往右行驶小车
TBcar = new ICar(tCop,TCar.topToBotton,17);//声明从上往下行驶小车对象
start();
}
public void start()
{
LRcar.start();
TBcar.start();
while(true)
{
try {Thread.sleep(50);}
catch(Exception e) { }
repaint();
}
}
public void paint(Graphics g)
{
super.paint(g);//调用父类的构造方法paint()
Color saveColor = g.getColor();
g.setColor(Color.black);
g.fillRect(0,180,400,40);//绘制横向通道
g.fillRect(180, 0, 40, 400);//绘制纵向车道
RLcar.drawCar(g);//绘制小车
TBcar.drawCar(g);//绘制小车
}
}
class TCar extends Thread{
public int lastPos = -1;//小车的最后位置
public int carPos = 0;//小车的当前位置
public int speed = 10;//初始化小车速度
public int driection = 1;//初始化小车的行驶方向
public final static int leftToRight = 1;
public final static int topToBotton = 2;
public ICar(TrafficCop tCop,int direction,int speed)
{
this.tCop = tCop;
this.speed = speed;
this.direction = direction;
}
public void run() {
while(true)
{
tCop.checkAndGo(carPos,speed);//线程同步
carPos += speed;//小车行进,每次增加speed
if(carPos>=400)
{carPos = 0;}
try {Thread.sleep(200);}
catch(InterruptedException e) {}
}
}
public void drawCar(Graphics g)
{
if(direction == ICar.leftToRight)
{
g.setColor(Color.gray);
g.fillOval(2+carPos, 185, 10, 10);
g.fillOval(26+carPos, 185, 10, 10);
g.fillOval(2+carPos,205,10,10);
g.fillOval(26+carPos, 205, 10, 10);
g.setColor(Color.green);
g.fillOval(0+carPos, 190, 40, 20);
lastPos = carPos;
}
else {
g.setColor(Color.gray);
g.fillOval(185, 2+carPos, 10, 10);
g.fillOval(185, 26+carPos, 10, 10);
g.fillOval(205, 2+carPos, 10, 10);
g.fillOval(205, 26+carPos, 10, 10);
g.setColor(Color.yellow);
g.fillRect(190, 0+carPos, 20, 40);
lastPos = carPos;
}
}
}
class TrafficCop
{
private boolean IntersectionBusy = false;
//定义同步化方法checkAndGo
public synchronized void checkAndGo(int carPos,int speed)
{
if(carPos + 40=180 && carPos +speed<=220)
{
while(IntersectionBusy)
{
try {wait();}
catch(InterruptedException e) { }
}
IntersectionBusy = true;
}
if(carPos + speed>220)
{
IntersectionBusy = false;
}
notify();
}
}
public class Example7_12{
public static void main(String[] args) {
new Road();
}
}