我需要初始化Array
n
中的Threads
。每个Thread
代表一个在Thread's Object
创建中随机初始化的数字。
程序应运行m
个迭代。在每次迭代中,Threads
号需要更新。如果Array
中的左右邻居都大于此Thread
,则Thread's
的值将在下一次迭代中获得+1。如果两个邻居的值都小于Thread's
,则Thread's
的值将为-1。否则,Thread's
的值将不会更改。
代码从GUI类中的代码行开始。该行是:
Controller cont = new Controller(n,m)
该代码仅一次在Controller类中输入更新的方法,然后所有Threads
都将进入睡眠状态,而无需实现更新的方法。
那是为什么?
这是我的代码:
public class Threads extends Thread
{
private int num;
private Controller cont;
private int toUpdate;
private int index;
public Threads(Controller c, int i)
{
num = (int)(Math.random() * 100 + 1); // random number between 1-100
cont = c;
index = i;
}
public void run()
{
for(int j = 1; j <= cont.getIterations(); j++)
{
toUpdate = cont.checkValue(this, this.getIndex());
cont.finished();
cont.threadWait();
num += toUpdate;
cont.updated();
cont.threadWait();
}
}
public int getValue()
{
return this.num;
}
public int getIndex()
{
return this.index;
}
}
public class Controller
{
private Threads[] threadsArray;
private int iterations;
private boolean finished = false;
private static int numOfThreads;
public Controller(int n, int m)
{
threadsArray = new Threads[n];
for(int i=0; i < threadsArray.length; i++)
threadsArray[i] = new Threads(this, i);
iterations = m;
numOfThreads = n;
printResults();
for(int i=0; i < threadsArray.length; i++)
threadsArray[i].start();
}
public synchronized void threadWait()
{
while(!finished)
{
try{ wait(); }
catch(InterruptedException e) {}
}
numOfThreads++;
waitForAll();
if(numOfThreads == threadsArray.length)
{
finished = false;
notifyAll();
}
}
public int checkValue(Threads t, int ind) //returns the thread's value to be updated. 1,-1 or 0.
public int getIterations()
{
return this.iterations;
}
public synchronized void finished()
{
numOfThreads--;
notifyAll();
if(numOfThreads == 0)
finished = true;
}
public void iteration()
{
for(int i=0; i < threadsArray.length; i++)
threadsArray[i].start();
}
public synchronized void updated()
{
numOfThreads--;
if(numOfThreads == 0)
{
printResults();
finished = true;
notifyAll();
}
}
public synchronized void waitForAll()
{
while(numOfThreads != threadsArray.length)
{
try{ wait(); }
catch(InterruptedException e) {}
}
}
public void printResults() // prints the result on each iteration.
}