问题描述:
两个线程,一个线程加载加载Mysql驱动,一个加载Oracle驱动,然后被阻塞在Class.forName()
Main:
public class ClassThread { public static void main(String[] args) { InnerMysqlThread it1 = new InnerMysqlThread(); InnerOracleThread it2 = new InnerOracleThread(); it1.start(); it2.start(); } }
加载Mysql:
public class InnerMysqlThread extends Thread { @Override public void run() { try { Class.forName("com.mysql.jdbc.Driver", true, this.getClass().getClassLoader()); System.out.println("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
加载Oracle:
public class InnerOracleThread extends Thread { @Override public void run() { try { Class.forName("oracle.jdbc.driver.OracleDriver", true, this.getClass().getClassLoader()); System.out.println("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
一直阻塞在java.sql.DriverManager中
线程dump为:
"Thread-1" prio=6 tid=0x00000000065bb800 nid=0xaa4 in Object.wait() [0x0000000006f4e000] java.lang.Thread.State: RUNNABLE at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at java.lang.Class.newInstance0(Class.java:357) at java.lang.Class.newInstance(Class.java:310) at sun.misc.Service$LazyIterator.next(Service.java:282) at java.sql.DriverService.run(DriverManager.java:664) at java.security.AccessController.doPrivileged(Native Method) at java.sql.DriverManager.loadInitialDrivers(DriverManager.java:506) at java.sql.DriverManager.initialize(DriverManager.java:612) at java.sql.DriverManager.registerDriver(DriverManager.java:281) - locked <0x000000077cf5cc38> (a java.lang.Class for java.sql.DriverManager) at oracle.jdbc.driver.OracleDriver.<clinit>(OracleDriver.java:188) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:249) at com.fable.hamal.node.core.classthreads.InnerOracleThread.run(InnerOracleThread.java:15) Locked ownable synchronizers: - None "Thread-0" prio=6 tid=0x00000000065ba800 nid=0x11c4 waiting for monitor entry [0x0000000006e4e000] java.lang.Thread.State: BLOCKED (on object monitor) at java.sql.DriverManager.registerDriver(DriverManager.java:280) - waiting to lock <0x000000077cf5cc38> (a java.lang.Class for java.sql.DriverManager) at com.mysql.jdbc.Driver.<clinit>(Driver.java:65) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:249) at com.fable.hamal.node.core.classthreads.InnerMysqlThread.run(InnerMysqlThread.java:15) Locked ownable synchronizers: - None
问题分析到线程:[Thread-0]被阻塞在lock <0x000000077cf5cc38>,而[Thread-1]持有lock <0x000000077cf5cc38>,但是却一直处在运行sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)方法中不结束,由于水平有限,不知道如何处理了。