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

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

最佳答案

如果获取ClassCastException,则意味着您还将不是MyThreadMyThread子类的Thread实现也传递到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 */
 }

10-08 13:15