我有两个 SWT 按钮 - “Start”和“Stop”以及一个 org.eclipse.swt.widgets.List。 在列表中,我保留了一个目录和一个打印机名称。
这个想法是将指定目录中的文件(PDF)发送到指定的打印机(print(inputPath,printerName)
)。
因此,当我单击“开始”时,会创建一个新的 Thread()
以调用 print(inputPath, PrinterName)
。
基本上,任务是:
每次单击“开始”时,都会创建一个新线程(每次 list.getItem(list.getSelectionIndices())
都不同)。
每次单击“停止”时 - 销毁特定线程(对于同一个 list.getItem(list.getSelectionIndices())
)。
我看到了一些带有 Future
、ExecutorService
、Runnable
等的示例,但我不知道如何将它们组合起来一起解决我的问题。
因此,任何帮助/提示将不胜感激。
最佳答案
只要有一个 Thread 类变量即可。当您单击启动按钮时,检查线程是否已存在,如果不存在,则创建新线程并启动它。 isRunning()
只是检查一个 boolean
来查看线程是否处于运行状态
if (thread == null || !thread.isRunning()){
thread = new MyThreadClass();
thread.start();
}
当您单击停止时,在线程中设置一个标志,告诉它现在已完成处理,类似于 setStop()
。
if (thread != null){
thread.setStop();
}
关于java - 使用线程(启动和停止它们),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16752658/