2016-03-07 32 views
0

新的線程類型。不能在循環中使用線程中的按鈕

我現在的代碼;

public boolean running = false; 
private void jStartButton1ActionPerformed(java.awt.event.ActionEvent evt){ 
    running = true; 
    (new Thread(new Home())).start(); 

}  
private void jStopButton2ActionPerformed(java.awt.event.ActionEvent evt) {           
    running = false; 
    System.out.println("trying to stop"); 
} 


public void run() { 
    while(running){ 
     //continously run code from a file thats updated every few seconds, running=false when its found what its looking for 
    } 

} 

jStopButton2正在處理中的運行設置爲false中調試,但它從來不承認由run()線程。 run()有它自己的running = false當它發現它尋找的東西時(它會停止while循環),它會建立它,但現在如果我想停止,我無法手動停止它。

我知道我有我的線程錯了,有什麼幫助嗎?難道是線程內的所有東西都被鎖定了嗎?所以它不能識別正在更改的運行布爾值?我將如何去改變它? o.o

任何幫助將不勝感激。

回答

1

你在這一點上

(new Thread(new Home())).start(); 

所以你的標誌running將被再次初始化(如果它不是靜態的) 因此,使用樓的同一個實例嘗試創建Home類的新實例,並且」會保持running

值我的意思是

(new Thread(this)).start(); 
+0

完美,謝謝:) – Pengiuns

0

這是一個非常簡單的synchronizat離子應用程序(基於使用running標誌的代碼)從主線程啓動第二個線程(您的Home類),等待一會,然後決定停止第二個線程。它給第二個線程留出時間來完成它的工作,並且/或者觀察running標誌已經被改變,並且最後完成主線程。

import java.util.*; 
import java.lang.*; 
import java.io.*; 

class Main 
{ 
    public static void main (String[] args) throws java.lang.Exception 
    { 
     Home home = new Home(); 
     Thread thread = home.jStartButton1ActionPerformed(null); 

     System.out.println("main thread sleeping"); 
     Thread.sleep(3000); 

     System.out.println("main thread deciding to stop secondary thread..."); 
     home.jStopButton2ActionPerformed(null); 

     System.out.println("main thread waiting for secondary thread to finish..."); 
     thread.join(); 

     System.out.println("main thread finished"); 
    } 
} 

class Home implements Runnable 
{ 
    public boolean running = false; 

    public Thread jStartButton1ActionPerformed(java.awt.event.ActionEvent evt){ 
     running = true; 

     Thread thread = new Thread(this); 
     thread.start(); 

     System.out.println("secondary thread started"); 

     // Returning thread instance so that the main thread can synchronize with it (wait for it to finish) 
     return thread; 
    } 

    public void jStopButton2ActionPerformed(java.awt.event.ActionEvent evt) {           
     running = false; 
     System.out.println("trying to stop"); 
    } 

    public void run() { 
     while(running){ 
      //continously run code from a file thats updated every few seconds, running=false when its found what its looking for 
      // Simulating work by sleeping. 
      try { 
       Thread.sleep(500); 
      } catch (Exception e) {} 
      System.out.println("secondary thread running..."); 
     } 
     System.out.println("secondary thread stopped"); 
    } 
} 

在你的榜樣的問題是,你每次做new Home(),從而創建一個新的可運行的實例(有自己的running版本),你無法控制。在上面的例子中,當前可運行的實例是啓動線程的實例,所以它確保將自己設置爲要由線程執行的代碼,從而保留對running字段的控制。主線程控制Home實例,因此它在調用Home實例的stop方法時還控制running字段。