2016-05-03 36 views
0

我正在嘗試同時執行兩個作業。我試圖做的事情之一是顯示一個計時器計時器,另一個正在移動球。Java同時執行

這是我創建的計時器,又撥打了moveBall方法

button.addChangeListener(new ChangeListener() { 

     int start = 0; 

     public void stateChanged(ChangeEvent e) { 

      ActionListener taskPerformer = new ActionListener() { 
       public void actionPerformed(ActionEvent evt) { 
        timeValue.setText(++start + " sec"); 
       } 
      }; 

      timer = new Timer(1000, taskPerformer); 
      timer.start(); 

      ball.moveBall(); 

     } 
    }); 

這是我moveBall方法

public void moveBall() { 

    Thread ball = new Thread() { 

     double counter = 0; 

     int t = (int) (2 * Vy/9.8); 

     public void run() { 
      try { 
       while (t >= 0) { 
        // calculate Vx and Vy 

        Ball.this.setX(Ball.this.getX() + Vx); 
        Ball.this.setY(Ball.this.getY() - Vy); 

        counter += 50; 

        if (counter == 1000) { 
         t--; 
         counter = 0; 
        } 

        paintingComponent.repaint(); 

        Thread.sleep(20); 
       } 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
    }; 

    ball.start(); 
} 

當我執行上面的代碼上的標籤顯示通過時間在球移動過程中根本沒有改變,當移動結束時,它取最後一個數字。

+0

你應該使用Swing定時更新兩個。如果您更容易創建多個Swing定時器 – ControlAltDel

+0

如果您不啓動「滾珠線程」,標籤是否更改其值? – Supahupe

+0

是的,當我沒有開始球線時它確實改變了它的值。 – Hunk

回答

0

這是一個例子兩個線程的兩次執行,Java的同時執行

public class ThreadExecutor extends Thread { 

    private String name; 

    private int executionCount; 

    public ThreadExecutor(final String name, final int executionCount) { 
     this.name = name; 
     this.executionCount = executionCount; 
    } 

    @Override 
    public void run() { 

     int count = 1; 

     while (count <= executionCount) { 
      System.out.println("Executing thread ".concat(name).concat(" : ") + count); 
      count++; 
     } 

    } 
} 

    public class Main { 

     public static void main(String args[]) { 

      final ThreadExecutor one = new ThreadExecutor("One", 1); 
      final ThreadExecutor two = new ThreadExecutor("Two", 2); 

      one.start(); 
      two.start(); 
     } 
} 
+0

它將構造函數的第二個參數的值分別增加到100和10,並查看併發性。 –

+0

執行線程一:1 執行的線程二:1 執行的線程之一:2 執行的線程二:2 執行的線程一:3 執行的線程二:3 執行的線程之一:4 執行的線程二:4 執行螺紋的一個:5 執行的線程二:5 執行的線程之一:6 執行的線程之一:7 執行的線程一:8 執行的線程之一:9 執行的線程一:10 執行的線程一:11 執行的線程的一個:12 執行線程一:13 執行線程一:14 執行線程一:15 ... –