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

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

 2010-05-14 00:00:00 来源:WEB开发网   
核心提示: ** 补疑 **有的童鞋可能会问:“你这个Demo根本没体现出来,每个线程里都有一个ThreadLocal对象;应该是一个ThreadLocal对象对应多个线程,Java 多线程同步问题的探究(五、你有我有全都有—— ThreadLocal如何解决并发安全性?)(6),你这变成了一对

********** 补疑 ******************

有的童鞋可能会问:“你这个Demo根本没体现出来,每个线程里都有一个ThreadLocal对象;应该是一个ThreadLocal对象对应多个线程,你这变成了一对一,完全没体现出ThreadLocal的作用。”

那么我们来看一下如何用一个ThreadLocal对象来对应多个线程:

/** *//**
 *
 * @author x-spirit
 */
public class ThreadDemo3 implements Runnable{
    private ThreadLocal<Student> stuLocal = new ThreadLocal<Student>(){
        @Override
        protected Student initialValue() {
            return new Student();
        }
    };
    public ThreadDemo3(){
       
    }
    public static void main(String[] args) {
        ThreadDemo3 td3 = new ThreadDemo3();
        Thread t1 = new Thread(td3);
        Thread t2 = new Thread(td3);
        Thread t3 = new Thread(td3);
        t1.start();
        t2.start();
        t3.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 线程 同步

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