我有一个大小为 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 组,其中一半将进行汇总,另一半将使用等待和通知进行添加。
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 的方式有关,但我不确定。
有帮助吗?
谢谢。