MyThread.java 967 Bytes
Newer Older
Luca Arrotta's avatar
Luca Arrotta committed
1 2 3 4 5 6 7 8 9 10 11 12
package semaphore;

import java.util.Random;

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;
13
        sem = s;
Luca Arrotta's avatar
Luca Arrotta committed
14 15 16
    }

    public void run() {
17 18
        //Simulate the thread is doing something else
        wasteSomeTime();
Luca Arrotta's avatar
Luca Arrotta committed
19 20 21
        System.out.println("Thread " + id + " wants to enter in the critical region");
        sem.enter();
        System.out.println("Thread " + id + " entered in the critical region!");
22 23 24

        //It takes some times to complete the work in the critical region
        wasteSomeTime();
Luca Arrotta's avatar
Luca Arrotta committed
25 26
        System.out.println("Thread " + id + " is going to get out from the critical region");
        sem.exit();
27 28
    }
    //End run
Luca Arrotta's avatar
Luca Arrotta committed
29 30 31 32 33 34

    private void wasteSomeTime() {
        int seconds = rnd.nextInt(10) + 1;
        try {Thread.sleep(seconds*1000);}
        catch(Exception ex) {ex.printStackTrace();}
    }
35
}
Luca Arrotta's avatar
Luca Arrotta committed
36