有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用线程(启动和停止线程)

我有两个SWT按钮——“开始”和“停止”以及一个org.eclipse.swt.widgets.List。 在列表中,我保留了一个目录和一个打印机名

其思想是将指定目录中的文件(PDF)发送到指定的打印机(print(inputPath, printerName)

因此,当我点击“开始”时,会创建一个新的Thread(),以便调用print(inputPath, printerName)

基本上,任务是:

每次单击“开始”都会创建一个新线程(每次list.getItem(list.getSelectionIndices())不同)

每次单击“停止”时,销毁特定线程(对于相同的list.getItem(list.getSelectionIndices())

我看到了一些关于FutureExecutorServiceRunnable等的例子,但我不知道如何将它们结合在一起,从而解决我的问题

因此,任何帮助/提示都将不胜感激


共 (1) 个答案

  1. # 1 楼答案

    只需要一个线程类变量。当你点击开始按钮时,检查一个线程是否已经存在,如果没有,那么创建一个新的线程并启动它。isRunning()只是检查一个boolean线程是否处于运行状态

    if (thread == null || !thread.isRunning()){
        thread = new MyThreadClass();
        thread.start();
    }
    

    单击stop时,在线程中设置一个标志,告诉它现在已经完成了处理,比如setStop()

    if (thread != null){
        thread.setStop();
    }