【问题标题】:Is is possible to get the reference of a running thread?是否可以获得正在运行的线程的引用?
【发布时间】:2019-03-26 07:45:27
【问题描述】:

这是我在社区的第一篇文章。欢迎任何cmets和建议。 我在端点http://ip:port/report 上有一个网络服务。该服务执行一个 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();
}

【问题讨论】:

  • Thread.currentThread()?
  • 显然我不能使用当前线程进行检查,因为它在不同的调用中。我需要的是获取我在调用期间传递的具有特定 ID 的线程,然后检查该线程的状态。
  • 您需要维护一个Map<Long, Thread>,将线程ID映射到线程。但要注意:一旦线程终止,id 可能会被重用!不过,可能还有其他(更好的)解决方案。但是这个问题有点太宽泛了。
  • 谢谢@Seelenvirtuose,现在我从你关于维护地图的回答中得到了一个新的想法。我还可以使用数据库中的表格来获取报告详细信息。但我仍在寻找一些方法来做到这一点。

标签: java multithreading


【解决方案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 方法的方式知道何时从映射中删除条目。

【讨论】:

  • 这很简短,很有帮助,谢谢@ernest_k。我目前正在阅读一篇关于 ExecutorService 和 ThreadPool 的文章。
【解决方案2】:

在您的工作 ID 的类中维护地图。 每当该线程被初始化时,在构造函数中传递 id,当它开始处理时将状态设置为正在运行,当它完成时,在 run 方法中结束执行之前,将状态设置为结束。如下所示

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
     }
}

【讨论】:

  • 感谢@Somil Aseeja 的建议。我也会考虑这个的。
猜你喜欢
  • 2021-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-20
  • 1970-01-01
  • 2010-09-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多