1

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

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 */    
 }
4

2 回答 2

0

解决方案是将我的线程用作可调用线程,并在 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();
    }
}
于 2015-03-17T03:55:25.263 回答
0

如果得到ClassCastException这意味着您将不是MyThread或子类的Thread 实现传递MyThread到您的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 */    
 }
于 2015-03-17T03:32:45.830 回答