所以我需要模拟一个十字路口。我现在有一个涂在JPanel上的十字路口和两个模拟汽车的汽车线。当一辆汽车靠近十字路口时,它应该停下来,稍等片刻,如果道路畅通,它应该穿过十字路口。所以每个线程都有一个move()方法,执行时间为40ms。 JPanel类:
public class Map extends JPanel {
private final Image mapa;
private Timer timer;
private Car s,s1;
public Map(){
s = new Car(1,1,0,550,265);
s1 = new Car(1,3,0,5,315);
ExecutorService es = Executors.newCachedThreadPool();
es.execute(s);
es.execute(s1);
ImageIcon temp = new ImageIcon(this.getClass().getClassLoader().getResource("resources/plansza.png"));
mapa = temp.getImage();
setPreferredSize(new Dimension(800,600));
timer = new Timer(40, new TL());
timer.start();
//auto.start();
//auto1.start();
}
@Override
public void paintComponent(Graphics g){
g.drawImage(mapa, 0, 0, this);
g.drawImage(s.getImage(), s.getX(), s.getY(), this);
g.drawImage(s1.getImage(), s1.getX(), s1.getY(), this);
System.out.println("40ms passed");
}
private class TL implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}
}
和Car类:
public class Car extends Thread{
Timer timer;
private int x , y;
private int predkosc, skad, gdzie;
private Image sam;
public Car(int predkosc, int skad, int gdzie, int x, int y)
{
//wspPocz();
this.predkosc = predkosc;
this.skad = skad;
this.gdzie = gdzie;
this.x = x;
this.y = y;
ImageIcon auto = new ImageIcon(this.getClass().getClassLoader().getResource("resources/sam.png"));
sam = auto.getImage();
}
//wtf ?!
@Override
public void run() {
timer = new Timer(40, new Przemieszczenie());
timer.start();
}
public int getX(){
return x;
}
public int getY(){
return y;
}
int dx=0;
private void move(){
if(skad == 3){
x = x + 1;
dx++;
}
else if(skad == 1)
{
x -= 1;
}
if(dx > 196){
try {
Thread.sleep(1000);
dx = 0;
} catch (InterruptedException ex) {
System.out.println("gowno");
}
}
}
public Image getImage(){
return sam;
}
private class Przemieszczenie implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
move();
}
}
}
好的,所以我只检查向东行驶的汽车。向西的那个应该开车穿过而不要停下来。但是当一个从西向东行进的人达到196个像素时Thread.sleep(1000);
导致整个应用程序停止响应一秒钟。第二辆车也停了下来,甚至主线也正在睡觉。
怎么了 ? move()方法在由Car扩展的Car类中。