Worker.java 810 Bytes
Newer Older
Gabriele Civitarese's avatar
Gabriele Civitarese committed
1 2 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
package countdownlatches;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

public class Worker implements Runnable {

    private Random rnd;
    private CountDownLatch countDownLatch;

    public Worker(CountDownLatch countDownLatch){
        this.countDownLatch = countDownLatch;
        this.rnd = new Random();
    }

    @Override
    public void run() {

        System.out.println("["+Thread.currentThread()+"] Thread started!");
        wasteSomeTime();
        System.out.println("["+Thread.currentThread()+"] Goodbye.");
        //decrease the countdown
        countDownLatch.countDown();

    }

    private void wasteSomeTime() {
        int seconds = rnd.nextInt(10) + 1;
        try {Thread.sleep(seconds*1000);}
        catch(Exception ex) {ex.printStackTrace();}
    }
}