package com.tool;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by xing on 2019-03-14.
*/
public class SuShuExample implements Callable<Boolean> {
private AtomicInteger atomicInteger;
private CountDownLatch countDownLatch;
private int num;
public SuShuExample(AtomicInteger atomicInteger, CountDownLatch countDownLatch,int num){
this.countDownLatch = countDownLatch;
this.atomicInteger = atomicInteger;
this.num = num;
}
@Override
public Boolean call() throws Exception {
countDownLatch.countDown();
int j=2;
while(num%j != 0){
j++;
if (num == j){
System.out.println(num);
atomicInteger.getAndIncrement();
System.out.println("count : " + atomicInteger.get());
Thread.sleep(10000);
return true;
}
}
return false;
}
}
package com.tool;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by xing on 2019-03-14.
*/
public class RunSuShu {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
AtomicInteger atomicInteger = new AtomicInteger(0);
CountDownLatch countDownLatch = new CountDownLatch(10);
ExecutorService executorService = Executors.newFixedThreadPool(4);
List<Future> futureList = new ArrayList<>();
for (int i =0;i<10;i++){
SuShuExample suShuExample = new SuShuExample(atomicInteger,countDownLatch,i);
futureList.add(executorService.submit(suShuExample));
}
//第一种方案;使用Future 获取 返回值
try {
int count = 0;
for (int j =0;j<futureList.size();j++){
try {
Boolean r = (Boolean)futureList.get(j).get();
if (r){
count ++;
}
} catch (ExecutionException e) {
e.printStackTrace();
}
}
System.out.println("sushu:" + count);
//方案二:引入countDownLatch\Actomic,应为是多线程要保证原子性
countDownLatch.await();
System.out.println("sushu:" + atomicInteger.get());
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
long endTime = System.currentTimeMillis();
System.out.println("time:" + String.valueOf(endTime - startTime));
executorService.shutdown();
}
}
}