Saturday, August 16, 2014

Java CountDownLatch and Thread

Example to use java.util.concurrent.CountDownLatch, synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.


package javacountdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaCountDownLatch {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        System.out.println("Start counting");
        
        CountDownLatch countDownLatch1 = new CountDownLatch(5);
        CountThread countThread1 = new CountThread("A", countDownLatch1, 5);
        CountDownLatch countDownLatch2 = new CountDownLatch(7);
        CountThread countThread2 = new CountThread("B", countDownLatch2, 7);

        try {
            countDownLatch1.await();
            System.out.println("A finished");
            countDownLatch2.await();
            System.out.println("B finished");
        } catch (InterruptedException ex) {
            Logger.getLogger(JavaCountDownLatch.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println(ex.toString());
        }
    }
}

class CountThread implements Runnable {

    int num_of_count = 5;
    CountDownLatch counter;
    String name;

    CountThread(String n, CountDownLatch c, int num) {
        name = n;
        counter = c;
        num_of_count = num;
        new Thread(this).start();
    }

    @Override
    public void run() {

        for (int i = 0; i < num_of_count; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(CountThread.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println(name + " : " + counter.getCount());
            counter.countDown();
        }
    }

}


- Read JavaFX version, Bind JavaFX ProgressBar.progressProperty() to DoubleProperty in Thread.

No comments:

Post a Comment