package thread.local; import java.util.concurrent.atomic.AtomicInteger; public class NumMake { private static final AtomicInteger uniqueId = new AtomicInteger(0); private static ThreadLocal<Integer> seqId = new ThreadLocal<Integer>() { public Integer initialValue() { return 0; } }; /** * @author jzh add 2011-12-20 * @return */ public int getNextSeqId() { seqId.set(seqId.get() + 1); return seqId.get(); } /** * * @author jzh add 2011-12-20 * @return */ public int getNetUniqueId() { return uniqueId.incrementAndGet(); } }
package thread.local; public class NumThread extends Thread { private NumMake num; private String name; public NumThread(String name, NumMake num) { super(name); this.num = num; this.name = name; } public void run() { for (int i = 0; i < 5; i++) { System.out.println(name + ", seqId = " + num.getNextSeqId() + ", uniqueId = " + num.getNetUniqueId()); try { Thread.sleep(200); } catch (Exception e) { e.printStackTrace(); } } } }
package thread.local; public class NumTest { /** * @author jzh 2011-12-20 * @param args */ public static void main(String[] args) { NumMake num = new NumMake(); Thread howskyThread = new NumThread("chanpinxue.cn", num); Thread jzhThread = new NumThread("jzh", num); howskyThread.start(); jzhThread.start(); } }