深入研究java.lang.ThreadLocal类ITeye - AG环亚娱乐集团

深入研究java.lang.ThreadLocal类ITeye

2019-01-13 15:59:39 | 作者: 浩初 | 标签: 线程,目标,获取 | 浏览: 2474

/**
 * Created by IntelliJ IDEA.
 * User: leizhimin
 * Date: 2007-11-23
 * Time: 10:53:33
 * 多线程下测验程序
 */
public class ThreadLocalDemo implements Runnable {
    //创立线程局部变量studentLocal,在后面你会发现用来保存Student目标
    private final static ThreadLocal studentLocal = new ThreadLocal();     public static void main(String[] agrs) {
        ThreadLocalDemo td = new ThreadLocalDemo();
        Thread t1 = new Thread(td, "a");
        Thread t2 = new Thread(td, "b");
        t1.start();
        t2.start();
    }     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 student = getStudent();
        student.setAge(age);
        System.out.println("thread " + currentThreadName + " first read age is:" + student.getAge());
        try {
            Thread.sleep(500);
        }
        catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        System.out.println("thread " + currentThreadName + " second read age is:" + student.getAge());
    }     protected Student getStudent() {
        //获取本地线程变量并强制转换为Student类型
        Student student = (Student) studentLocal.get();
        //线程初次履行此办法的时分,studentLocal.get()肯定为null
        if (student == null) {
            //创立一个Student目标,并保存到本地线程变量studentLocal中
            student = new Student();
            studentLocal.set(student);
        }
        return student;
    }
}
版权声明
本文来源于网络,版权归原作者所有,其内容与观点不代表AG环亚娱乐集团立场。转载文章仅为传播更有价值的信息,如采编人员采编有误或者版权原因,请与我们联系,我们核实后立即修改或删除。

猜您喜欢的文章