java中ThreadLocal类使用测试

来源:互联网 发布:喷绘王类似软件 编辑:程序博客网 时间:2024/05/17 04:43

public class TestThreadLocal {

    public static void main(String[] args) {
        new MyThread("NO1 ").start();
        new MyThread("NO2 ").start();
        new MyThread("NO3 ").start();
        new MyThread("NO4 ").start();
        new MyThread("NO5 ").start();

    }

}

class MyThreadLocal {

    private static int nextSerialNum = 0;

    private static ThreadLocal serialNum = new ThreadLocal() {

        protected synchronized Object initialValue() {
            return new Integer(++nextSerialNum);
        }
    };

    public static int get1() {
        return ((Integer) (serialNum.get())).intValue();
    }

    private static final ThreadLocal ConnContext = new ThreadLocal() {

        protected synchronized Object initialValue() {
            Integer num = new Integer(5);

            return num;
        }
    };

    public static int get2() {
        return ((Integer) (ConnContext.get())).intValue();
    }
}

class MyThread extends Thread {
    String name = null;

    public MyThread(String name) {
        this.name = name;
    }

    public void run() {
        System.out.println(this.name + "  get1  " + MyThreadLocal.get1());
        System.out.println(this.name + "  get2  " + MyThreadLocal.get2());

    }
}
 

原创粉丝点击