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

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

 2010-05-14 00:00:00 来源:WEB开发网   
核心提示: 还记得我们在第三篇的上半节引出的那个例子么?几个线程修改同一个Student对象中的age属性,为了保证这几个线程能够工作正常,Java 多线程同步问题的探究(五、你有我有全都有—— ThreadLocal如何解决并发安全性?)(2),我们需要对Student的对象进行同步,下面我们对这个程序进

还记得我们在第三篇的上半节引出的那个例子么?几个线程修改同一个Student对象中的age属性。为了保证这几个线程能够工作正常,我们需要对Student的对象进行同步。

下面我们对这个程序进行一点小小的改造,我们通过继承Thread来实现多线程:

/**
 *
 * @author x-spirit
 */
public class ThreadDemo3 extends Thread{
    private ThreadLocal<Student> stuLocal = new ThreadLocal<Student>();
    public ThreadDemo3(Student stu){
        stuLocal.set(stu);
    }
    public static void main(String[] args) {
        Student stu = new Student();
        ThreadDemo3 td31 = new ThreadDemo3(stu);
        ThreadDemo3 td32 = new ThreadDemo3(stu);
        ThreadDemo3 td33 = new ThreadDemo3(stu);
        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  下一页

Tags:Java 线程 同步

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