简体   繁体   中英

java swing paint with multithreads

I have been trying to make a maze which two rectangles will move over depending on some rules.The problem is I have to use multithread and a thread pool.I never tried multithreading and a bit new in Java.I wrote some codes .I test it .it is working but when I wanted to show current thread id (to prove two thread working simultaneously ), I am getting four different thread numbers.Namely I am not sure it is multithreaing.Please if u have an idea, tell me what i must do.Thanks.

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);
              }
        }

( I didnt put here decision() method a bit long.it just calculates new x,y coordinates)

When you use an ExecutorService , you don't have to do anything that directly works with threads. The service does it for you. In the constructor you are making (and starting a thread) to execute your run method. Then when you add the them to the pool, the executor service takes the 2 Runnables and runs them in the two threads in the pool.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM