2014-06-28 24 views
0

我正在處理線程,並且我希望在我打開Cal_JInternalFrame時運行此代碼。它運行了第一次,但每當我重新打開框架,它不會再運行。我在整個申請的退出時間使用t1.interrupted()。代碼是:Java中的線程命令選項是什麼?

Thread t1 = new Thread(new Runnable() { 
    @Override 
    public void run() { 
     while (!t1.isInterrupted()) {  
      // ......... Oil Calculation Thread ... 
      int price = (Integer.parseInt(jLabel22.getText())); 
      int qty = (Integer)jSpinner8.getValue(); 
      int totalOil =qty * price; 
      jTextField19.setText(String.valueOf(totalOil));  
     } 
    } 
}); 

t1.start()是在主框架的構造函數中。

線程原始的方法destroy()stop()resume()suspend()已棄用,所以我不能使用這些。我現在可以如何stopresume一個線程?如果我的線程t1被中斷,如何重新啓動或重新運行?

+0

也許未來就是你要找的。 –

+1

你的代碼在你設想的不同級別上是*錯誤*:Swing是**不是線程安全的**並且你不能從任何線程查詢或修改除UI線程以外的任何Swing組件。 http://stackoverflow.com/questions/13873198/where-can-i-find-a-description-of-swing-as-a-single-threaded-model-in-the-javado你可以使用'EventQueue.invokeLater '和'EventQueue.invokeAndWait'來安排代碼在UI線程上運行,如果你當前在不同的線程上。不這樣做會以非常意想不到的方式破壞你的程序。 –

回答

0

線程不能被重新使用。對於需要在不同時間在單獨線程上執行的任務,請使用單線程執行程序。

看來你需要一個工作線程。由於標準線程無需額外工作就無法重用,我們使用工作線程來管理應該多次執行的任務。

ExecutorService executors = Executors.newSingleThreadExecutor(); 

這樣,您可以重複使用單個線程多次執行代碼。它也使您可以使用未來像這樣的異步回調:

class Demo { 
    static ExecutorService executor = Executors.newSingleThreadExecutor(); 

    public static void main(String[] args) { 
      Future<String> result = executor.submit(new Callable<String>() { 
       public String call() { 
        //do something 
        return "Task Complete"; 
       } 
      }); 

      try { 
       System.out.println(result.get()); //get() blocks until call() returns with its value 
      }catch(Exception e) { 
       e.printStackTrace(); 
      } 
    } 
} 

您現在可以重新使用executor爲您想要的任務。它通過execute(Runnable)方法接受Runnable

我看到你在使用Swing。使用EventQueue.invokeLater(Runnable)將所有搖擺代碼發佈到事件調度線程。應在事件調度線程上調用getText()setText()以避免不一致。

0

我該如何停止並恢復一個線程?

你不行。相反,你需要讓你的線程停止並恢復自身。例如:

private boolean wake; 

public synchronized void wakeup() { 
    this.wake = true; 
    this.notify(); 
} 

public void run() { 
    while (!t1.isInterrupted()) {  
     // do stuff ... 
     wake = false; 
     synchronized (this) { 
      while (!wake) { 
       try { 
        this.wait(); 
       } catch (InterruptedException ex) { 
        t1.interrupt(); // reset the interrupted flag 
       } 
      } 
     } 
    } 
} 

當其他線程想要獲得這一個做一些事情時,調用wakeup()方法擴展Runnable對象上。

如果我的線程t1被中斷,又怎麼能恢復或運行?

正如你所寫的那樣,No.一旦線程從run()方法調用中返回,它就不能被重新啓動。您需要創建並啓動全新的Thread


但是,你要做的是不安全的。正如@Erwin指出的,t1線程調用Swing對象的方法(如jTextField19)並不安全。您應該只從Swing事件派發線程調用Swing對象的方法。

參考:

相關問題