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

时间:2023-03-09 06:42:10
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();
} }