java线程中断,线程为空

标签 java multithreading

我是线程新手,正在尝试复制一个在我的网络应用程序中中断线程的简单示例。我有下面的类(ComputeResults 有其他变量和函数、setter/getters 等,但这是我无法工作的新代码):

@ManagedBean(name="results")
@RequestScoped
public class ComputeResults implements Serializable{

    Thread scan;
    public void testrun() {
    scan = new Thread(new Runnable() {
        @Override
        public void run() {
            int i = 0;
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    i++;
                    if (i == 1) {
                        scan.interrupt();
                    }
                } 
                catch (Exception e) {
                    Thread.currentThread().interrupt();
                }
                catch (Throwable t) {
                    System.out.println("Thrown test: "+t.getMessage());
                }
            }
        }
    });

    scan.start();
}

    public void stoprun() {
        if(scan != null){
            scan.interrupt();
        }
    }
}

在我的界面中,我有一个启动线程的按钮:

<p:commandLink action="submit" value="" onclick="testdialog.show()" oncomplete="testdialog.hide()" actionListener="#{results.testrun}" update="messages, runmsg, @form results" />

还有一个尝试中断它的方法:

<p:commandButton action="submit" value="Cancel Test" onclick="testdialog.hide()" actionListener="#{results.stoprun}" update="messages, runmsg" />

问题是“stoprun”函数将“scan”视为空,我不确定为什么。在 testrun() 中添加 scan.interrupt() 效果很好。我想过使用 Thread.currentThread().interrupt() 但当我调用 stoprun 时,当前线程 ID/名称似乎不同。

最佳答案

这是因为 bean 是 @RequestScoped - 每个 HTTP 请求(= 按钮单击)都会获取一个新实例。

您至少需要将其设为@Scope("session")

关于java线程中断,线程为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12068230/

相关文章:

c# - 是否可以同时使用线程并发和并行?

java - Groovy + Java接口(interface)继承问题

java - `ArrayList::get` 是线程安全的吗?

multithreading - 在 Linux 2.6+ 中替换系统调用(syscalls)

multithreading - 像特斯拉的 AutoPilot 这样的系统如何跟上不断变化的多进程请求?

multithreading - Google Guava Cache 是否在同一个线程上加载?

java - 无法处理部署的阶段结构

java - 帮助识别该记录器

java 使用JAXP读取xml根节点描述

c++ - 每个线程都有自己的堆栈吗?