2014-06-28 22 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对象的方法。

参考:

相关问题