Thread的实现化过程:
public Thread() { init(null, null, "Thread-" + nextThreadNum(), 0); }
private void init(ThreadGroup g, Runnable target, String name, long stackSize) { init(g, target, name, stackSize, null); }
private void init(ThreadGroup g, Runnable target, String name, long stackSize, AccessControlContext acc) { .... if (security == null || isCCLOverridden(parent.getClass())) //下面是关键两行: this.contextClassLoader = parent.getContextClassLoader(); else this.contextClassLoader = parent.contextClassLoader; //从上面可以看出,具有父子关系(不是继承关系)的线程的ContextClassLoader都一样,在一般的应用 //都是由main线程衍生出许多子线程,所以他们的ContextClassLoader都一样。 this.inheritedAccessControlContext = acc != null ? acc : AccessController.getContext(); this.target = target; setPriority(priority); if (parent.inheritableThreadLocals != null) this.inheritableThreadLocals = ThreadLocal.createInheritedMap(parent.inheritableThreadLocals); /* Stash the specified stack size in case the VM cares */ this.stackSize = stackSize; /* Set thread ID */ tid = nextThreadID(); }
那么ContextClassLoader的意义何在?
父Classloader可以使用当前线程Thread.currentthread().getContextLoader()中指定的classloader中加载的类。 颠覆了父ClassLoader不能使用子Classloader或者是其它没有直接父子关系的Classloader中加载的类这种情况。 这个就是Context Class Loader的意义