WEB开发网
开发学院软件开发Java Java 多线程同步问题的探究(五、你有我有全都有—... 阅读

Java 多线程同步问题的探究(五、你有我有全都有—— ThreadLocal如何解决并发安全性?)

 2010-05-14 00:00:00 来源:WEB开发网   
核心提示: 讲到这里,我想不少朋友一定已经看出来了:ThreadLocal的initialValue()方法是需要被覆盖的,Java 多线程同步问题的探究(五、你有我有全都有—— ThreadLocal如何解决并发安全性?)(5),于是,ThreadLocal的正确使用方法是:将ThreadLocal以内部

讲到这里,我想不少朋友一定已经看出来了:ThreadLocal的initialValue()方法是需要被覆盖的。

于是,ThreadLocal的正确使用方法是:将ThreadLocal以内部类的形式进行继承,并覆盖原来的initialValue()方法,在这里产生可供线程拥有的本地变量值。

这样,我们就有了下面的正确例程:

/**
 *
 * @author x-spirit
 */
public class ThreadDemo3 extends Thread{
    private ThreadLocal<Student> stuLocal = new ThreadLocal<Student>(){
        @Override
        protected Student initialValue() {
            return new Student();
        }
    };
    public ThreadDemo3(){
       
    }
    public static void main(String[] args) {
        ThreadDemo3 td31 = new ThreadDemo3();
        ThreadDemo3 td32 = new ThreadDemo3();
        ThreadDemo3 td33 = new ThreadDemo3();
        td31.start();
        td32.start();
        td33.start();
    }
    @Override
    public void run() {
        accessStudent();
    }
    public void accessStudent() {
        String currentThreadName = Thread.currentThread().getName();
        System.out.println(currentThreadName + " is running!");
        Random random = new Random();
        int age = random.nextInt(100);
        System.out.println("thread " + currentThreadName + " set age to:" + age);
        Student student = stuLocal.get();
        student.setAge(age);
        System.out.println("thread " + currentThreadName + " first  read age is:" + student.getAge());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        System.out.println("thread " + currentThreadName + " second read age is:" + student.getAge());
    }
}

上一页  1 2 3 4 5 6 7 8  下一页

Tags:Java 线程 同步

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接