我正在处理线程,我想在每次打开Cal_JInternalFrame
时运行此代码。它只运行一次,但每当我重新打开框架时,它都不会再次运行。我在整个应用程序的退出时使用t1.interrupted()
。代码是:
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()
已被弃用,因此我无法使用这些方法。我现在如何stop
和resume
线程?如果我的线程t1
被中断,它怎么能恢复或再次运行?
答案 0 :(得分: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
}
}
}
}
}
当其他一些线程希望让这个线程做某事时,调用扩展的runnable对象上的wakeup()
方法。
如果我的线程t1被中断,它怎么能恢复或再次运行?
正如您所写,否。一旦线程从run()
方法调用返回,就无法重新启动。您需要创建并启动全新的Thread
。
但是,你要做的是不安全。正如@Erwin指出的那样,t1
线程调用Swing对象(如jTextField19
)上的方法是不安全的。您应该只从Swing事件调度线程调用Swing对象上的方法。
参考:
答案 1 :(得分:0)
线程无法重复使用。对于需要在不同时间在单独的线程上执行的任务,请使用单个线程执行程序。
好像你需要一个工作线程。由于标准线程在没有额外工作的情况下不可重用,我们使用工作线程来管理应该多次执行的任务。
ExecutorService executors = Executors.newSingleThreadExecutor();
通过这种方式,您可以重复使用单个线程多次执行代码。它还允许您使用Future进行异步回调,如下所示:
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
来完成您想要的任务。它通过Runnable
方法接受execute(Runnable)
。
我看到你正在使用Swing。使用EventQueue.invokeLater(Runnable)
将所有swing代码发布到Event Dispatch Thread。应在事件调度线程上调用getText()
和setText()
以避免出现差异。