线程通常是从Runnables创建的。有没有办法从 a 创建线程Callable?
public class AddNumImmediately implements Callable {
private int minRange;
private int maxRange;
private Set<Integer> primeNumberList;
private int step;
public AddNumImmediately(int minRange, int maxRange, Set<Integer> primeNumberList, int step) {
this.minRange = minRange;
this.maxRange = maxRange;
this.primeNumberList = primeNumberList;
this.step = step;
}
@Override
public Object call() {
for (int i = minRange; i <= maxRange; i += step) {
if (PrimeChecker.isPrimeNumber(i)) {
primeNumberList.add(i);
}
}
return primeNumberList;
}
}
然后我尝试通过线程运行我的 Callable:
public void setup(int min, int max, int threadNumber) throws InterruptedException {
Set<Integer> primeNumberList = new LinkedHashSet<>();
List<Thread> threadList = new ArrayList<>();
for (int i = 0; i < threadNumber; i++) {
threadList.add(new Thread(String.valueOf(new AddNumImmediately(min, max, primeNumberList, threadNumber))));
}
for (Thread thread : threadList) {
thread.start();
}
for (Thread thread : threadList) {
thread.join();
}
System.out.println(primeNumberList);
}
我知道Callables 可以由 an 运行Executor,但是有可能以某种方式运行它们Thread吗?
当年话下
呼唤远方
相关分类