2017-03-03 60 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 –