MyThread.java 985 Bytes
Newer Older
1 2
package semaphoreAPI;

3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
import java.util.Random;
import java.util.concurrent.Semaphore;


public class MyThread extends Thread {
	private Random rnd;
	private int id;
	private Semaphore sem;
	
	MyThread(Random r, int i, Semaphore s) {
		rnd = r;
		id = i;
		sem=s;
	}
	
  public void run() {
	wasteSomeTime(); //Simulate the thread is doing something else
	System.out.println("Thread " + id + " wants to enter in the critical region");
	try{
		sem.acquire();
	}
	catch(InterruptedException ie) {
		ie.printStackTrace();
	}

	System.out.println("Thread " + id + " entered in the critical region!");
	wasteSomeTime(); //it takes some times to complete the work in the critical region

	System.out.println("Thread " + id + " is going to get out from the critical region");
	sem.release();
  }//end run
  
  private void wasteSomeTime() {
		int seconds = rnd.nextInt(10) + 1;
		try {
			Thread.sleep(seconds*1000);
		}
		catch(Exception ex) {
			ex.printStackTrace();
		}
  }
} //end class