package cn.test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestUtil {
public static void main(String[] args) {
K k = new K();
ExecutorService pool = Executors.newCachedThreadPool();
for(int i=1;i<101;i++){
pool.execute(new AddThread(k,i));
}
pool.shutdown();
// while(!pool.isTerminated()){
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
System.out.println("結果為:"+k.getTotal());
}
}
class AddThread implements Runnable{
public AddThread(K k, int add) {
this.k = k;
this.add = add;
}
private K k;
private int add;
@Override
public void run() {
k.add(add);
}
}
class K{
private int total=0;
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public synchronized void add(int k){
this.total=total+k;
}
}