直接贴代码了
package test; public class TestThreadLocal { public static void main(String[] args) { /*ExecutorService exce = Executors.newCachedThreadPool(); for(int i=0;i<10;i++){ exce.execute(new Thread(new TestThread(),"this is thread:"+i)); } exce.shutdown(); } */ //一个公共的对象 TestI testI = new TestI(); //创建一个ThreadLocal来维护这个对象 LocalObject localObject = new LocalObject(); localObject.addTestI(testI); // System.out.println(localObject.getTestI().getI()); for(int i=0;i<10 ;i++){ new Thread(new TestThread(localObject),"this is thread:"+i).start(); } } } class LocalObject{ //创建一个ThreadLocal 用来维护对象TestI private ThreadLocal<TestI> testIocal = new ThreadLocal<TestI>(); public void addTestI(TestI testI){ testIocal.set(testI); } public TestI getTestI(){ return testIocal.get(); } public void doSomeThing(){ getTestI().setI(); } } class TestThread implements Runnable{ private LocalObject localObject ; public TestThread(LocalObject localObject){ this.localObject = localObject; } private int i=10; @Override public void run() { while(this.localObject.getTestI().getI()>0){ this.localObject.doSomeThing(); i--; if(this.localObject.getTestI().getI()!=i){ System.out.println(Thread.currentThread().getName()+"not matched"); } // System.out.println(Thread.currentThread().getName()+"::"+LocalObject.getTestI().getI()); } } } class TestI { private int i=10; public void setI(){ i--; } public int getI(){ return i; } }
报错是Exception in thread "this is thread:1" java.lang.NullPointerException
at test.TestThread.run(TestThreadLocal.java:75)
就是run方法里面找不到对象,但是我通过构造方法注入了一个对象了呀。怎么回事 搞了2天了。。。