我有一个大小为n的数组,其中填充了数字1..n。
每次使用两个元素时,我需要使用m个线程对此数组求和,将它们相加并将总和插回到数组中。
这是我试图做的事情。
首先是同步部分
public class MultiThreadedSum {
private ArrayBuffer ArrayBufferInst;
private int Sum;
private boolean Flag;
public MultiThreadedSum(ArrayBuffer ArrayBufferInst)
{
this.ArrayBufferInst = ArrayBufferInst;
Sum = 0;
Flag = false;
}
public synchronized void Sum2Elements()
{
while(Flag)
{
try {wait();}
catch (InterruptedException e){}
}
Flag = true;
if (ArrayBufferInst.RetunrSize() < 2)
{
return;
}
System.out.println("Removing 2 elements.");
Sum = ArrayBufferInst.Sum2Elements();
notifyAll();
}
public synchronized void InsertElement()
{
while(!Flag)
{
try {wait();}
catch (InterruptedException e){}
}
Flag = false;
System.out.println("Inserting the sum.");
ArrayBufferInst.InsertElement(Sum);
notifyAll();
}
public int RetunrSize()
{
return ArrayBufferInst.RetunrSize();
}
}
我已经将m个线程拆分为2个组,其中一半将进行汇总,一半将使用wait和notify进行添加。
public class Sum2ElementsThread implements Runnable{
private MultiThreadedSum MultiThreadedSumInst;
public Sum2ElementsThread( MultiThreadedSum MultiThreadedSumInst)
{
this.MultiThreadedSumInst = MultiThreadedSumInst;
}
@Override
public void run() {
while(MultiThreadedSumInst.RetunrSize() > 1)
{
MultiThreadedSumInst.Sum2Elements();
}
}
}
public class InsertThread implements Runnable{
private MultiThreadedSum MultiThreadedSumInst;
public InsertThread( MultiThreadedSum MultiThreadedSumInst)
{
this.MultiThreadedSumInst = MultiThreadedSumInst;
}
@Override
public void run() {
while(MultiThreadedSumInst.RetunrSize() > 1)
{
MultiThreadedSumInst.InsertElement();
}
}
}
以下是主要内容的一部分:
ArrayBufferInst = new ArrayBuffer(n);
MultiThreadedSumInst = new MultiThreadedSum(ArrayBufferInst);
ExecutorService Threads = Executors.newCachedThreadPool();
for (i = 0; i < m/2; i++)
{
Threads.execute( new Sum2ElementsThread(MultiThreadedSumInst) );
}
for (; i < m; i++)
{
Threads.execute( new InsertThread(MultiThreadedSumInst) );
}
while (MultiThreadedSumInst.RetunrSize() > 1){}
Threads.shutdown();
缓冲区
public class ArrayBuffer {
private ArrayList<Integer> ArrayBufferInst;
public ArrayBuffer(int SizeOfBuffer)
{
int i;
ArrayBufferInst = new ArrayList<>(SizeOfBuffer);
for (i = 0; i < SizeOfBuffer; i++)
{
ArrayBufferInst.add(i, i+1);
}
}
public int Sum2Elements()
{
if (ArrayBufferInst.size() < 2)
{
return -1;
}
return ArrayBufferInst.remove(0) + ArrayBufferInst.remove(1);
}
public void InsertElement(int Elem)
{
ArrayBufferInst.add(Elem);
}
public int RetunrSize()
{
return ArrayBufferInst.size();
}
}
我收到了很多java.lang.IndexOutOfBoundsException和RangeCheck错误,这可能与我实现Sum2Elements的方式有关,但我不确定。
任何帮助人员?
感谢。
答案 0 :(得分:2)
在ArrayList {a, b, c}
if (ArrayBufferInst.size() < 2)
{
return -1;
}
return ArrayBufferInst.remove(0) + ArrayBufferInst.remove(1);
然后ArrayBufferInst.remove(0)
将删除并返回a
,将ArrayBufferInst
更改为{b, c}
。然后拨打ArrayBufferInst.remove(1)
将移除 c ,这不是您想要的。所以只需将1更改为0。