群里一同胞发了一段1000个线程做累加的代码,用的是Runable与Thread来做累加 如下是他的代码:
/**
* Created by ZuoQB on 2015-07-29.
*/
public class ThreadPlus {
private static int value = 0;
public synchronized static void inc() {
value++;
}
public static void main(String arges[]) throws InterruptedException{
ExecutorService execu = Executors.newFixedThreadPool(10);
long start = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
execu.execute(new Runnable() {
public void run() {
ThreadPlus.inc();
System.out.println(value);//add by me
}
});
}
execu.shutdown();
long end = System.currentTimeMillis();
System.out.println("------------------"+value);
System.out.println(end-start);
}
}
最后运行的时候没有得到预期的结果1000。我在线程run()中添加了一句输出代码,
发现计算结果是有1000的,代码最后那句输出早早的执行了,其实当执行输出的时候那1000个线程还没有执行完成,所以输出结果不准确。
下面是我用的Future和Callable按照原来的逻辑修改后的代码。
import java.util.concurrent.*;
/**
* Created by ZuoQB on 2015-07-29.
*/
public class ThreadTest implements Callable<Integer> {
private static volatile int value = 0;
public synchronized static void inc() {
value++;
}
@Override
public Integer call() throws Exception {
ThreadTest.inc();
return value;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService execu = Executors.newFixedThreadPool(10);
Future<Integer> future = null;
long start = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
future = execu.submit(new ThreadTest());
try {
System.out.println(future.get());
} catch (Exception e) {
System.out.println("here can catch Exception,the exception is "+e.getMessage());
execu.shutdownNow();
}
}
execu.shutdown();//reduce accept new task
long end = System.currentTimeMillis();
System.out.println("------------------"+future.get());
System.out.println(end-start);
}
}