java多线程快速入门(十六)

ThreadLocal关键字实现每个线程有自己的变量

package com.cppdy;

class Number {

    private int num;

    public static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {

            return 0;
        }
    };

    public Number(int num) {
        this.num = num;
    }

    public int getNum() {
        int temp = threadLocal.get();
        threadLocal.set(temp+1);
        int count=threadLocal.get();
        return count;
    }
}

public class ThreadDemo12 extends Thread {

    private Number n;

    public ThreadDemo12(Number n) {
        this.n = n;
    }

    @Override
    public void run() {
        System.out.println(getName() + "--" + n.getNum());
    }

    public static void main(String[] args) throws Exception {
        Number n1 = new Number(0);
        ThreadDemo12 mt1 = new ThreadDemo12(n1);
        ThreadDemo12 mt2 = new ThreadDemo12(n1);
        ThreadDemo12 mt3 = new ThreadDemo12(n1);
        mt1.start();
        mt2.start();
        mt3.start();
    }

}

 

posted @ 2018-11-25 16:51  知识追求者  阅读(135)  评论(0编辑  收藏  举报