我一直在尝试制作一个迷宫,其中两个矩形将根据某些规则移动。问题是我必须使用多线程和线程池。我从未尝试过多线程,并且在 Java 中有点新。我写了一些代码.我测试了它。它正在工作,但是当我想显示当前线程ID(以证明两个线程同时工作)时,我得到了四个不同的线程号。也就是说,我不确定它是多线程的。如果你有一个想法,请,告诉我我必须做什么。谢谢。
class Action extends JPanel{
Robot robot1,robot2;
public static Random rndm=new Random();
public Action() throws InterruptedException{
ExecutorService pool=Executors.newFixedThreadPool(2);
robot1=new Robot(0,560); // starts random free position
robot2=new Robot(0,560);
pool.submit(robot1);
System.out.println("rbt1 olustu");
pool.submit(robot2);
System.out.println("rbt2 olustu");
pool.shutdown();
}
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
robot1.MyDraw(g);
System.out.println("robot1 drawing");
robot2.MyDraw(g);
System.out.println("robot2 drawing");
}
class Robot implements Runnable{
int x;
int y;
Robot(int xCor,int yCor){
this.x=xCor;
this.y=yCor;
new Thread(this).start();
}
public void MyDraw(Graphics g){
if(end==false){
Image img1 = Toolkit.getDefaultToolkit().getImage("cat.jpg");
g.drawImage(img1, x, y,null);}
else{
g.setColor(Color.white);
g.drawRect(x, y, 40,40);
}
}
public void run() {
if(Frame.control==true){
while(true){
if(end==false){
decision(x,y);
visitedCell[x/40][y/40]+=1;
try{
Thread.sleep(300);
repaint();
}catch(Exception ex){
ex.printStackTrace();
}
System.out.println(Thread.currentThread().getId());
}
else{
Thread.currentThread().interrupt();
System.out.println("Thread dead");
Frame.button4.setEnabled(true);
}
}
(我没有把decision()方法放在这里有点长。它只是计算新的x,y坐标)
最佳答案
当您使用ExecutorService
时,您不必执行任何直接与线程一起使用的操作。该服务会为您完成。在构造函数中,您正在创建(并启动线程)来执行 run 方法。然后,当您将它们添加到池中时,执行程序服务将获取 2 个 Runnables 并在池中的两个线程中运行它们。
关于java swing 多线程绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8329751/