public class Test {
public static void main(String[] args) throws InterruptedException {
//创建两个线程 分配堆内存空间 获取一个线程引用
ExecutorService executor=Executors.newFixedThreadPool(8);
WE we = new WE();
we.setIw(1);
executor.submit(new Clas(we));
we.setIw(2);
System.out.println("gg");
executor.submit(new Clas(we));
executor.shutdown();
System.out.println(we.getIw());
}
}
public class WE {
private volatile Integer iw;
public WE() {
super();
}
public WE(Integer iw) {
super();
this.iw = iw;
}
//线程类
public class Clas implements Runnable {
private WE we;
public Clas(WE we) {
System.out.println("构造"+Thread.currentThread().getName()+"------"+we);
this.we = we;
System.out.println("构造this"+Thread.currentThread().getName()+"------"+this.we);
}
@Override
public void run() {
//查看对象变化 System.out.println(Thread.currentThread().getName()+"------"+we);
System.out.println(Thread.currentThread().getName()+we.getIw());
we.setIw(8);
}
结果分析
我在主线程里面创建了两个线程,并且完成了构造,将一个对象的引用赋值到线程内部,当线程使用对象时全都是去堆内存取的数据,所以取的一个改变了值。