FreeOZ论坛
标题:
JDK 1.5 Concurrent库的一个sample
[打印本页]
作者:
key
时间:
3-8-2009 18:23
标题:
JDK 1.5 Concurrent库的一个sample
刚才自己写的一个东西,混用ThreadLocal(这个是1.2的API了),java.util.concurrent.Callable/ExecutorServices/Executors,
java.util.concurrent.atomic.AtomicInteger。不过我的程序只是用来测试ThreadLocal以及Callable的用法,
没有线程控制(事实上也没有必要,因为没有共享数据)。
1 import java.util.concurrent.*;
2 import java.util.concurrent.atomic.*;
3 import static java.lang.System.*;
4
5 public class ThreadLocalTest3 {
6 private static final AtomicInteger ai = new AtomicInteger();
7
8 public static void main(String [] args) {
9 Callable<Integer> call = new Callable<Integer>(){
10 ThreadLocal<Integer> v = new ThreadLocal<Integer>() {
11 @Override protected Integer initialValue() {
12 return ai.getAndIncrement();
13 }
14 };
15
16 @Override public Integer call() throws InterruptedException{
17 int x = v.get(); //initialize thread local variable
18 int w = (int)(Math.random() * 10000);
19 Thread.sleep(w);
20 out.println(x + ", " + v.get() + " : " + w);
21 return v.get();
22 }
23 };
24
25 ExecutorService execs = Executors.newCachedThreadPool();
26 for(int k=0; k<100; k++){
27 execs.submit(call);
28 }
29 execs.shutdown();
30 }
31 }
复制代码
欢迎光临 FreeOZ论坛 (https://www.freeoz.org/bbs/)
Powered by Discuz! X3.2