是否可以获取正在运行的线程的引用?

时间:2019-03-26 07:45:28

标签: java multithreading

这是我在社区上的第一篇文章。欢迎任何意见和建议。 我在端点http://ip:port/report上有一个Web服务。该服务执行一个Runnable类。执行Runnable之后,是否可以通过单独的服务调用检查/监视线程?

我仍在工作,正在搜索诸如ExecutorService之类的东西,但还是没有运气。还有其他方法吗?请提出一些可能的解决方案,我可以检查一下。对不起,我的语法。我希望我可以在下面的示例代码中清楚地说明这一点。

我的代码是这样的。

在以下位置运行线程:http://ip:port/report

public String runReport {

    // Run the the runnable
    Report report = new Report();
    String threadName = "REPORT1";
    Thread t = new Thread(report, threadName);
    t.start();

    // return thread some details
    return t.getId() + "|" + t.hashCode();
}

我的可运行类

public class Report {

    private String status;

    @Override
    public void run() {
        //Update status
        setStatus("Running");

        //... do stuff

        //Update status
        setStatus("End")
    }

    // Getter and Setter
}

我在http://ip:port/report/check/some_param上的检查器类

public String check( int threadId ) {
    // Search the thread by threadId and check the current status
    //Report.getStatus();
}

2 个答案:

答案 0 :(得分:1)

使用线程ID可能不是最好的主意,尤其是因为您可能使用重用线程的池。 一种简单的解决方案是为您的工作生成ID,并维护可用于读取状态的地图。

例如,您可以将唯一的ID用作任务ID:

Map<String, Report> jobs = new ConcurrentHashMap<>();
ExecutorService executorService = Executors.newFixedThreadPool(10); //just an example

public String runReport {

    // Run the the runnable
    Report report = new Report();

    //For a numeric sequence, you can use something like AtomicLong
    String jobId = UUID.randomUUID().toString();
    jobs.put(jobId, report);

    //using a thread pool may be a better idea.
    executorService.submit(report);

    // return the job ID
    return jobId;
}

要查看状态,只需阅读地图即可:

public String check(String jobId) {
    return jobs.get(jobId).getStatus(); //remember null checks
}

然后,您只需要根据期望调用check方法的方式,知道何时从地图上删除条目。

答案 1 :(得分:1)

在您的工作ID类别中维护地图。 无论何时初始化该线程,都应在构造函数中传递ID,并在其开始处理时将状态设置为“运行”,并在完成时将其结束,然后在run方法的执行方法中将状态设置为“ end”。像下面这样

public void run(){
     try{
     jobsMap.put(this.jobId, "Running");
     // your business logic here
     jobsMap.put(this.jobId,"Completed");
     } catch(Exception e){
       jobsMap.put(this.jobId,"Failed. Reason -"+e.getMessage);
       // exception handling
     }
}