【发布时间】:2017-03-15 18:16:34
【问题描述】:
这是我的代码:
class Processor implements Runnable {
private int id;
private Integer interaction;
private Set<Integer> subset;
Iterator<Integer> iterator;
ArrayList<Integer> par;
public Processor(int id, Integer interaction, Set<Integer> subset, Iterator<Integer> iterator, ArrayList<Integer> par) {
this.id = id;
this.interaction = interaction;
this.subset = subset;
this.par = par;
this.iterator = iterator;
}
public void run() {
System.out.println("Starting: " + this.id);
if (this.par.contains(this.interaction)) {
this.subset.add(this.interaction);
increaseScore(this.subset);
if (!this.subset.contains(this.interaction)) {
//TELL ALL OTHER THREADS TO STOP WHILE THIS THREAD REMOVES THE VALUE FROM THE ITERATOR
iterator.remove();
}
}
System.out.println("Completed: " + this.id);
}
}
public class ConcurrentApp {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(4);
ArrayList<Integer> par1 = new ArrayList < Integer > ();
long start = System.nanoTime();
int i = 1;
while ((par1.size() > i)) {
for (Iterator<Integer> iterator = par1.iterator(); iterator.hasNext();) {
Integer interaction = iterator.next();
ArrayList<Integer> removed = new ArrayList<Integer> (par1);
removed.remove(interaction);
ArrayList<Set<Integer>> subsets = getSubsets(removed, i);
for (int j = 0; j < subsets.size(); j++) {
executor.submit(new Processor(j, interaction, subsets.get(j), iterator, par1));
}
executor.shutdown();
System.out.println("All tasks submitted");
try {
executor.awaitTermination(1, TimeUnit.DAYS);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("All tasks completed");
i++;
}
long end = System.nanoTime();
System.out.println("Program Completed in: " + (end - start) * 0.000000001);
}
}
我的代码流程如下:
从一个名为 par 的整数数组列表开始,遍历此集合中的每个元素(我们将称为 A)
从par中去掉A得到B
查找大小为 i 的所有子集(在 1 到 par.size() 的范围内)
[多线程] 对于每个大小为 i 的子集,在 A 中加回以获得新的集合 C。然后找到删除时 C 的得分增加最多的值。 [条件]如果该值为 A,则从 par 中删除 A 并移动到 par 中的下一个元素。如果 A 没有删除任何大小为 i 的子集,则继续到 par 中的下一个元素。
我的意图是让每个线程使用其中一个子集并执行上述多线程步骤,直到其中一个线程满足条件。我认为我正确地实现了这一点,但由于我是并发编程的新手,所以我会欣赏第二组眼睛。
问题 1: 在上面的多线程步骤中,我怎样才能告诉线程池中的所有其他工作线程停止他们的任务并在单个线程遇到时返回线程池 条件?
问题 2: 有没有办法让多个线程同时处理不同大小的子集的不同集合(因此一次有多个 i 值)并让多个线程执行 上面的多线程步骤对于给定的一组子集(这是我已经完成的)?本质上,这就像把我的整个工作分成两个任务:任务 1 是查看大小为 1、2、3...par.size() 的子集集,任务 2 是查看集合中的每个元素子集。
感谢您的帮助!
【问题讨论】:
标签: java multithreading concurrency java.util.concurrent