Skip to content

Instantly share code, notes, and snippets.

@sahib
Created December 12, 2011 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sahib/1468249 to your computer and use it in GitHub Desktop.
Save sahib/1468249 to your computer and use it in GitHub Desktop.
import java.lang.Math;
import java.util.Arrays;
class A3 extends Thread {
private static final int N = 3;
private int myid = 0;
public volatile static Integer array[] = {0,0,0};
A3(int i)
{
myid = i;
}
public void run()
{
rand_sleep();
access();
}
/* accessing both tools */
public void access()
{
int lefttool = get_left();
/*locking left tool */
get_left_tool(1);
System.out.println(myid + " nimmt linken schluessel " + Arrays.toString(array));
get_right_tool(1);
System.out.println(myid + " nimmt rechten schluessel " + Arrays.toString(array));
System.out.println(myid + " arbeitet mit beiden schluesseln "+ Arrays.toString(array));
rand_sleep();
get_right_tool(-1);
System.out.println(myid + " legt rechten schluessel zurueck " + Arrays.toString(array));
get_left_tool(-1);
System.out.println(myid + " legt linken schluessel zurueck " + Arrays.toString(array));
}
/* simple random sleep func */
private void rand_sleep()
{
try
{
Thread.sleep((long)(Math.random()*1000));
}
catch(Exception e) {}
}
/* calculates left tool position */
private int get_left()
{
if (myid!=0)
{
return myid-1;
}
else
{
return N-1;
}
}
/* gets left tool */
private void get_left_tool(int inc)
{
int left_tool_pos = get_left();
/* Wait till available */
while(array[left_tool_pos] != 0) { /* wait */ }
synchronized(array[left_tool_pos])
{
array[left_tool_pos]+=inc;
}
}
/* gets right tool */
private void get_right_tool(int inc)
{
/* Wait till available */
while(array[myid] != 0) { /* wait */ }
synchronized(array[myid])
{
array[myid]+=inc;
}
}
public static void main (String [] args)
{
A3 mech[] = new A3[N];
for (int i=0; i<N ; ++i)
{
mech[i] = new A3(i);
mech[i].start();
}
for (int i=0 ;i<N ;++i )
{
try{
mech[i].join();
}
catch(Exception e)
{}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment