2011-11-30 113 views
0

我一直在努力使兩個矩形將移動取決於一些規則的迷宮。問題是我必須使用多線程和一個線程pool.I從來沒有嘗試過多線程和Java中有點新。我寫了一些代碼。我測試它。它正在工作,但是當我想要顯示當前線程ID(以證明兩個線程同時工作),我得到四個不同的線程數。名稱我不確定它是多線程。請if你有一個想法,告訴我我必須做什麼。謝謝。java swing swing與多線程

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

(我不把這裏的決定()方法的位long.it只計算新的x,y座標)

回答

1

當您使用ExecutorService,你不必做任何事情,直接作用與線程。該服務爲您提供幫助。在構造函數中,你正在創建(並啓動一個線程)來執行你的run方法。然後,當您將它們添加到池中時,執行程序服務將採用2個Runnables並在池中的兩個線程中運行它們。

+0

這是可以的謝謝你。但我也想加載不同的圖像到MyDraw()方法中的每個線程。例如robot1 cat.jpg,robot2 dog.jpg.I嘗試了不同的東西,他們沒有工作。現在我可以加載兩個線程相同的圖片:( – Ecrin

+0

@ user1073777:將想要加載的圖像作爲參數傳遞給構造函數。「Runnable」實際上只關心繪圖,而不是它繪製的內容。 – unholysampler

+0

是的,它工作好主意:) – Ecrin