📄 example7_8.java
字号:
import java.applet.Applet;
import java.awt.*;
public class Example7_8 extends Applet implements Runnable
{
Thread AnimThread=null;
ICar LRcar,TBcar;
TrafficCop tCop;
public void init()
{
resize(400,400);
tCop=new TrafficCop();
LRcar=new ICar(tCop,ICar.leftToRight,16);
TBcar=new ICar(tCop,ICar.topToBotton,17);
}
public void start()
{
if (AnimThread==null)
{
AnimThread=new Thread(this);
AnimThread.start();
if (LRcar!=null && TBcar!=null)
{
LRcar.start();
TBcar.start();
}
}
else
{
AnimThread.resume(); //恢复线程运行
if (LRcar!=null){LRcar.resume(); }
if (TBcar!=null){TBcar.resume(); }
}
}
public void stop()
{
AnimThread.suspend(); //挂起线程
if (LRcar!=null){LRcar.suspend(); }
if (TBcar!=null){TBcar.suspend(); }
}
public void run()
{
while(true)
{
try{Thread.sleep(50);}
catch(InterruptedException e){}
repaint();
}
}
public void paint(Graphics g)
{
Color saveColor=g.getColor();
g.setColor(Color.black);
g.fillRect(0,180,400,40);
g.fillRect(180,0,40,400);
LRcar.drawCar(g);
TBcar.drawCar(g);
}
public void update(Graphics g)
{
if(!isValid())
{
paint(g);
return;
}
LRcar.drawCar(g);
TBcar.drawCar(g);
}
}
class ICar extends Thread
{
public int lastPos=-1;
public int carPos=0;
public int speed=10; //初始化小车速度
public int direction=1;//初始化小车的行驶方向
public TrafficCop tCop;
public final static int leftToRight=1;
public final static int topToBotton=2;
public ICar(TrafficCop tCop)
{
this(tCop,ICar.leftToRight,10);
}
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;
if (carPos>=400)
{ carPos=0; }
try{Thread.sleep(200);}
catch(InterruptedException e){}
}
}
public void drawCar(Graphics g) //绘制小车
{
if(direction==ICar.leftToRight) //方向判断
{
if(lastPos>=0) //位置判断
{
g.setColor(Color.black);
g.fillRect(0+lastPos,185,40,32);
}
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
{
if(lastPos>=0)
{
g.setColor(Color.black);
g.fillRect(185,0+lastPos,32,40);
}
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;
}
}
public void updateCar(Graphics g) //更新
{
if (lastPos!=carPos)
{
drawCar(g);
}
}
}
class TrafficCop //该类用于ICar线程的控制
{
private boolean IntersectionBusy=false;
//同步化方法
public synchronized void checkAndGo(int carPos,int speed)
{
if(carPos+40<180 && carPos+40+speed>=180 && carPos+speed<=220)
{
while(IntersectionBusy)
{
try{ wait();}
catch(InterruptedException e){}
}
IntersectionBusy=true;
}
if(carPos+speed>220)
{
IntersectionBusy=false;
}
notify(); //线程退出等待状态
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -