1. 程式人生 > >java多執行緒快速入門(十六)

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(); } }