Yes, this is a homework assignment, but I have tried everything possible and can't come up with a possible. The point of this assignment is to illustrate that, before implementing the dekker's algorithm / peterson's algorithm, it is very likely that two processes will not go one after another.
import java.util.*;
public class myProcess
{
private static final Random R = new Random();
private int id;
public myProcess(int i){
id = i;
}
private static void delay(int value){
try{
java.lang.Thread.sleep(R.nextInt(value));
}
catch(InterruptedException e){
}
}
public void run(){
System.out.println("");
delay(20);
System.out.println(this.id + " is starting");
delay(20);
System.out.println("LINE ONE");
delay(20);
System.out.println("LINE TWO");
delay(20);
System.out.println("LINE THREE");
delay(20);
System.out.println(this.id+ " is ending ");
delay(20);
}
public static void main(String [] args){
final int N = 2;
myProcess[] t = new myProcess[N];
for(int i = 0; i < N; i++){
t[i] = new myProcess(i);
t[i].run();
}
}
Right now the output is
0 is starting
LINE ONE
LINE TWO
LINE THREE
0 is ending
1 is starting
LINE ONE
LINE TWO
LINE THREE
1 is ending
but it should be all mixed up to illustrate that processes don't necessarily wait for another one to finish.
I tried other methods of defining run() such as
String[] statements = new String[5];
statements[0] = "Thread " + this.id + " is starting iteration ";
statements[1] = "We hold these truths to be self-evident, that all men are created equal,";
statements[2] = "that they are endowed by their Creator with certain unalienable Rights,";
statements[3] = "that among these are Life, Liberty and the pursuit of Happiness.";
statements[4] = "Thread " + this.id+ " is done with iteration ";
for(int i = 0; i< 5; i++){
System.out.println(statements[i]);
delay(20);
}
but it still does not return to me any "wrong outputs"
What am I doing so wrong that's making the output so right?