ThreadLocal的使用

http://docs.oracle.com/javase/6/docs/api/java/lang/ThreadLocal.html了解了一些基本使用,但是发现里面的代码有问题

检查了一下,原来是getCurrentThreadId()应该return uniqueNum.get()而不是return uniqueId.get()

改写如下:

// Each thread has its own 'thread-ID' even if 'uniqueNum' is static
class UniqueThreadIdGenerator {
    private static final AtomicInteger uniqueId = new AtomicInteger(0);

    private static final ThreadLocal<Integer> uniqueNum = 
        new ThreadLocal<Integer>() {
            @Override
            protected Integer initialValue() {
                return uniqueId.getAndIncrement();
            }
        };

    public static int getCurrentThreadId() {
        return uniqueNum.get();
    }
}

class Runner implements Runnable {
    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                System.out.println(UniqueThreadIdGenerator.getCurrentThreadId());
                TimeUnit.MILLISECONDS.sleep(500);
            }
        } catch (Exception e) {
        }
    }
}

public class Foo { 
    public static void main(String[] args) throws IOException { 
        ExecutorService exec = Executors.newCachedThreadPool();
        exec.execute(new Runner());
        exec.execute(new Runner());
        System.in.read();
        exec.shutdownNow();
    }
}
原文地址:https://www.cnblogs.com/qrlozte/p/3162191.html