packagesemaphore;importjava.util.Random;publicclassMyThreadextendsThread{privateRandomrnd;privateintid;privateSemaphoresem;MyThread(Randomr,inti,Semaphores){rnd=r;id=i;sem=s;}publicvoidrun(){wasteSomeTime();//Simulate the thread is doing something elseSystem.out.println("Thread "+id+" wants to enter in the critical region");sem.enter();System.out.println("Thread "+id+" entered in the critical region!");
System.out.println("Thread "+id+" is going to get out from the critical region");sem.exit();}//end runprivatevoidwasteSomeTime(){intseconds=rnd.nextInt(10)+1;try{Thread.sleep(seconds*1000);}catch(Exceptionex){ex.printStackTrace();}}}//end class