线程对对象的操作不解

package com.yuan;

import java.io.Serializable;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestThreadPool {
	private static int produceTaskSleepTime = 3000;
	private static int consumeTaskSleepTime = 2000;
	private static int produceTaskMaxNumber = 1;

	public static void main(String[] args) {
		// 构造一个线程池
		ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2,4, 3,
				TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3),
				new ThreadPoolExecutor.DiscardOldestPolicy());
		for (int i = 1; i <= produceTaskMaxNumber; i++) {
			try {
				// 产生一个任务,并将其加入到线程池
				String task = "task@ " + i;
				User u  = new User();
				u.setId(1);
				u.setName("yqf");
				System.out.println("put " + task);
				ThreadPoolTask t =	new ThreadPoolTask(u);
				threadPool.execute(t);
				// 便于观察,等待一段时间
				Thread.sleep(produceTaskSleepTime);
				System.out.println("MAIN TASK:"+ u.getName());
				System.out.println(" t user: " +  t.getUser().getName());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 线程池执行的任务
	 * @author hdpan
	 */
	public static class ThreadPoolTask implements Runnable, Serializable {
		private static final long serialVersionUID = 0;
		// 保存任务所需要的数据
		private User threadPoolTaskData;
		ThreadPoolTask(User tasks) {
			this.threadPoolTaskData = tasks;
		}
		public void run() {
			// 处理一个任务,这里的处理方式太简单了,仅仅是一个打印语句
			System.out.println("start .." + threadPoolTaskData);
			/*try {
				// //便于观察,等待一段时间
				Thread.sleep(consumeTaskSleepTime);
			} catch (Exception e) {
				e.printStackTrace();
			}*/
			System.out.println("ThreadPoolTask task:" + threadPoolTaskData);
			threadPoolTaskData = null;
			//threadPoolTaskData.setName("3333");
		}
		public User getUser(){
			return threadPoolTaskData;
		}
	}

}

 以上代码是主线程构造一个User对象,将user对象传入线程,线程里面对user进行了=null操作。然后回主线程,发现去取System.out.println("MAIN TASK:"+ u.getName());
的时候,还是可以取到,但是调用System.out.println(" t user: " +  t.getUser().getName());
确实空指针。

 

而且如果你在子线程里面对user进行了修改名字操作,System.out.println("MAIN TASK:"+ u.getName());
也是可以找到子线程操作后的user的。

 

不明白为何会这样??

你可能感兴趣的:(thread)