【问题标题】:How to access thread objects inside custom threadpool executor's methods?如何访问自定义线程池执行器方法中的线程对象?
【发布时间】:2015-03-17 02:15:25
【问题描述】:

我想访问自定义线程池执行程序中的可运行对象中的数据。如果我尝试访问之前/之后的执行方法,我会得到类转换异常。我该如何解决这种情况。

public class MyThread implements Runnable 
{
  String key;

  public void run(){ /* Do something */}  
}

public class MyExecutor extends ThreadPoolExecutor
{

  @Override
  protected void beforeExecute(Thread paramThread, Runnable paramRunnable)
  {
             MyThread mt = (mt)paramRunnable; 

  }

  @Override
  protected void afterExecute(Runnable paramRunnable, Throwable paramThrowable) 
 {
       MyThread mt = (mt)paramRunnable; 
    /* Need to access "key" inside MyThread */    
 }

【问题讨论】:

  • 您尝试投射 paramRunnable 吗?
  • 我试过了。编辑了上面的代码。当我遇到问题时尝试进行类型转换。

标签: java multithreading executorservice threadpoolexecutor executors


【解决方案1】:

如果得到ClassCastException,这意味着您将不是MyThreadMyThread 的子类的线程实现也传递到您的MyExecutor。因此,为了修复它,您只需在投射之前进行instanceof 检查。

public class MyExecutor extends ThreadPoolExecutor
{

  @Override
  protected void beforeExecute(Thread paramThread, Runnable paramRunnable)
  {
         if(paramRunnable instanceof MyThread) {
             MyThread mt = (MyThread)paramRunnable; 
         }

  }

  @Override
  protected void afterExecute(Runnable paramRunnable, Throwable paramThrowable) 
 {
       if(paramRunnable instanceof MyThread) {
           MyThread mt = (MyThread)paramRunnable; 
       }
       /* Need to access "key" inside MyThread */    
 }

【讨论】:

    【解决方案2】:

    解决方案是使用我的线程作为可调用,并在futuretask响应中获取响应。下面的实现解决了我的解决方案。

        protected void afterExecute(Runnable paramRunnable, Throwable paramThrowable) {
    
        super.afterExecute(paramRunnable, paramThrowable);
        FutureTask<String> task = (FutureTask<String>) paramRunnable;
        try {
            String a = task.get();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-09-30
      • 1970-01-01
      • 2016-02-28
      • 1970-01-01
      • 2018-12-11
      • 2014-08-27
      • 2017-12-29
      • 1970-01-01
      • 2010-09-27
      相关资源
      最近更新 更多