2017-03-03 31 views
1

IM樣的新Java線程和我剛碰到了一組項目的一個問題:Java線程:無法創建新的主題和殺戮/斷開舊線

//編輯:程序是一個JFrame這需要一種「重新啓動」來加載properties文件的更改。

我們有一個程序,您可以更改某些屬性。 爲使更改生效,該程序需要用新的JVM重啓/新推出的(在我看來,?)

問題是以下幾點:

我已經做了這actualy開始我們的程序中的線程並且稍後,更改將觸發程序創建一個新線程。這工作,但我無法殺死舊線程。如果我嘗試這樣做(「X」或編程)我同時殺死兩個實例。 所以實際上沒有2個線程? - 否則他們應該被分開處理,不是嗎?

另一方面,當使用Thread.currentThread().interrupt()兩個實例將保持,但即時通訊不能從字面上做任何事情。

主題首發:

public static void createNewInstance() { 
prog = new Runnable() { 
     @Override 
     public void run() { 
      try { 
       //loading propertie data into String[] array.. 
       Start.main(String[] array); 
       while (true) { 
         if (!isRunning) { 
          currentThread().interrupt(); 
          createNewInstance(); 
          isRunning = !isRunning; 
         } 
       } 
      } catch (InterruptedException e) { 
       Thread.currentThread().interrupt(); 
      } 
     } 
    }; 
    new Thread(prog).start(); 
} 

,並在更改事件:

 MyThread.isRunning = false; 
     Thread.currentThread().interrupt(); 

由於這是新的給我,我想不出我應該如何做到這一點的IM感謝任何種類的建議以及我迄今爲止所犯的任何錯誤。 (對不起,任何一種錯誤 - 我不是一個母語)

在此先感謝!

----解決方法解決:----

在我的情況下propertie變化相關的新的語言設置:DE - > EN
我的留言:
public class Messages { private static String bundle_name = "com.ttr.language.messages" + new PropertiesClass().getProperty("lang"); //$NON-NLS-1$ private static ResourceBundle resource_bundle = ResourceBundle.getBundle(bundle_name);

然後我說這個方法來Messages類:

public static void updateProperties(String language) { bundle_name = "com.ttr.language.messages" + language; resource_bundle = ResourceBundle.getBundle(bundle_name); }

,並用它在我的計劃:

props.setProperty("lang", "EN"); < - 例如 Messages.updateProperties(props.getProperty("lang"));
//dispose window and start login

+0

你居然中斷當前線程,而不是所期望的中斷之一。您需要在'createNewInstance()'中創建的線程實例正確中斷。 –

+0

另外,我敢肯定你不需要線程來中斷自己。你可以讓它離開你的Runnable的主體,此時它會正常停止。 –

+0

嗨,感謝您的快速回復!我是否必須一直將其傳遞給變更事件?我們有很多類......或者我可以像'getInstanceOf(MyThread).currentThread()'那樣做一些事情? – Slajoc

回答

1

比方說XThread是實現你的functionality.When線程的變化被觸發,你可以打電話terminateThread()停止上一個正在運行的線程並調用getInstance()以使用新屬性運行新線程。

class XThread implements Runnable{ 

     private static Thread rT = null; 
     private XThread() 
     {} 
     public static void terminateThread() 
     { 
      rT = null; 
     } 

     public static Thread getInstance() 
     { 
      if(rT==null) 
      { 
       rT = new Thread(new XThread()); 
      } 
      return rT; 
     } 

     public void run() 
     { 
     //whatever functionality you want to add 
     } 
    } 

希望這有助於:)

+0

嗨,謝謝你。也許我做錯了,但我不能讓這個工作。 如果即時通訊使用某事像 '公共無效的run(){ 的System.out.println( 「開始」); Thread.sleep(5000); System.out.println(「exit」); terminateThread();' 它只是像一個魅力和打印退出後立即終止。 但是,如果我嘗試啓動我的程序,而不是第一個'了System.out.println(「開始」);'它運行程序,運行'的Thread.sleep()',但不事後終止我的程序。 。? – Slajoc

+0

嘗試像這樣... https://jpst.it/UMR2。原諒我不正確的縮進。你是否使用'''SwingUtilites.invokeLater()'''來運行你的GUI代碼。 –

+0

一個有用的鏈接使用'的invokeLater(http://stackoverflow.com/questions/3551542/swingutilities-invokelater-why-is-it-needed –