qq_41257374 2017-12-03 07:54 采纳率: 0%
浏览 1154

java,在eclipse中运行,运行出错,各位大佬帮我看看哪里出bug了

/*线程同步示例,十字交通路口*/
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();
}
}

  • 写回答

1条回答 默认 最新

  • threenewbee 2017-12-03 10:19
    关注

    程序是你写的还是哪里抄来的,如果是后者,对应的jar包有导入么?这是swt程序,需要swing的包的。

    评论

报告相同问题?

悬赏问题

  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思