下面的代码由于未初始化外部成员变量而引发空指针异常。 它正在为可运行变量抛出NPE in run方法。我已经在newFixedThreadPool方法中初始化了ConcurrentLinkedQueue类型的本地valiable,并调用参数化构造函数来初始化runnable成员变量。
顺便说一下,当我直接初始化runnable变量而不创建任何局部变量时,代码将成功运行。
有人能解释一下吗
import java.util.concurrent.ConcurrentLinkedQueue; public class MyExecuterService { private ConcurrentLinkedQueue<Runnable> runnables; //private AtomicBoolean execute=AtomicBoolean.true; private PoolWorkerThread poolWorkerThreads[]; public MyExecuterService() {} public MyExecuterService(ConcurrentLinkedQueue<Runnable> runnables,PoolWorkerThread poolWorkerThreads1[]) { this.runnables=runnables; poolWorkerThreads=poolWorkerThreads1; } private class PoolWorkerThread extends Thread{ @Override public void run() { while(true) { System.out.println(runnables.size()+"runnable"+runnables); synchronized (runnables) { if(runnables.size()==0) { try { runnables.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } else { Runnable task=runnables.poll(); task.run(); //notify(); } } } } } public MyExecuterService newFixedThreadPool(int i) { ConcurrentLinkedQueue<Runnable> runnableQueue= new ConcurrentLinkedQueue<Runnable>(); PoolWorkerThread [] threads= new PoolWorkerThread[i]; for (int j = 0; j < i; j++) { threads[j]= new PoolWorkerThread(); threads[j].start(); } return new MyExecuterService(runnableQueue, threads); } public void execute(Runnable runnable) { System.out.println(runnables.size()); synchronized(runnables) { runnables.add(runnable); runnables.notify(); } } public ConcurrentLinkedQueue<Runnable> getRunnables() { return runnables; } public void setRunnables(ConcurrentLinkedQueue<Runnable> runnables) { this.runnables = runnables; } }
这个 NullPointerException 是由于 MyExecuterService 未初始化。
NullPointerException
MyExecuterService
您创建了 MyExecuterService公司 对象中包含参数 new FixedThreadPool(int i) 方法,但由于此方法属于 MyExecuterService公司 所以要访问此方法,必须创建 MyExecuterService公司 反对。 只有你才能访问这个对象。
MyExecuterService公司
new FixedThreadPool(int i)
现在,由于创建 具有空参数构造函数的对象,因此不会初始化数据成员。
检查一下你要调用的对象 the newFixedThreadPool(int i) 方法并确保使用参数化构造函数创建该对象。
the newFixedThreadPool(int i)
顺便说一下,你的设计 MyExecuterService公司 类是一种假设。