java swing 多线程绘制

标签 java multithreading swing

我一直在尝试制作一个迷宫,其中两个矩形将根据某些规则移动。问题是我必须使用多线程和线程池。我从未尝试过多线程,并且在 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/

相关文章:

java - RabbitMQ + Spring 集成 : Message conversion from queue bound to a topic exchange

java - JAXB解析复杂的xml

java - 从java中的线程中获取异常

java - 调度程序可以挂起一个线程并执行另一个线程/工作吗?

java - 如何使用 Action 监听器从按钮获取背景颜色

java - 在Jmeter中提取数组中的json

java - 来自配置的 JBPM 服务任务分配输入

java - 线程作为 GC 根

java - JPanel repaint()方法及调试

java - 在 SWING 中按住左键单击