import java.util.ArrayList;
public class CheckThread implements Runnable {
private int x;
private ArrayList<CheckThread> arrayList;
private Monitor monitor;
private int index;
public CheckThread(int x, Monitor monitor, ArrayList<CheckThread> arrayList,int index) {
this.x = x;
this.monitor = monitor;
this.arrayList = arrayList;
this.index = index;
}
public int getX()
{
return x;
}
@Override
public void run() {
for( int i=0 ; i<monitor.getChecks(); i++) {
System.out.println(("check " + i + "INDEX" + index));
int result = checkNeighbours(); // checking the thread compare to his neighbours
monitor.setBool(index); // changing the thread's status in the monitor to "true"
try {
isDone(result,index); //
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void isDone(int res, int index) throws InterruptedException { // this method checks if the threads c
System.out.println("ISDONE?");
if (monitor.isFinished()) { // if all the array is true, that means all threads have checked themselves and are ready to be changed
System.out.println(arrayList);
monitor.setBooleansFalse(); // after all threads were checked, they are set as false in order to be ready for next iteration
System.out.println("Before Notify of Index " + index);
notifyAll(); // notify all
System.out.println("After Notify of index " + index);
}
else {
System.out.println("NO");
System.out.println("Wait of Thread " + index);
wait();
}
System.out.println("Increase Decrease INDEX " + index);
this.x+= res;
}
public synchronized int checkNeighbours() { // this method checks for each thread his status (bigger,smaller or balanced between his neighbours)
int [] indexes = setNeighbours(index); //setting the neighbours of the thread
int pre = indexes[0];
int next = indexes[1];
if(isSmall(index,pre,next)) // cheking if he is smaller
return 1;
if (isBig(index,pre,next)) //cheking if he is bigger
return -1;
return 0; // otherwise he is balanced
}
@Override
public String toString() {
return Integer.toString(x);
}
public boolean isBig(int index, int pre, int next)
{
return arrayList.get(index).getX() > arrayList.get(pre).getX() && arrayList.get(index).getX() > arrayList.get(next).getX();
}
public boolean isSmall(int index, int pre, int next)
{
return arrayList.get(index).getX() < arrayList.get(pre).getX() && arrayList.get(index).getX() < arrayList.get(next).getX();
}
public int [] setNeighbours(int index) // setting the neigbours
{
int [] returnVal = new int[2];
if ( index ==0 )
{
returnVal[0] = arrayList.size() -1;
returnVal[1] = index +1;
}
else if(index == arrayList.size() -1)
{
returnVal[0] = index -1;
returnVal[1] = 0;
}
else
{
returnVal[0] = index -1;
returnVal[1] = index +1;
}
return returnVal;
}
}