JUC-CountDownLatch 노트

3010 단어
1. CountDownLatch 소개
CountDownLatch는 지정된 스레드 수량을 완성하기 전에 다른 스레드가 완성되기를 동기화하는 보조 클래스로 개인적인 느낌과 계수기의 차이가 많지 않다.
2. CountDownLatch 예


import java.util.concurrent.CountDownLatch;

/**
 * Created by wuhao on 15-12-23.
 */
public class CountDownLatchDemo {
    public static void main(String[] args) {
        //      3,     
        CountDownLatch countDownLatch=new CountDownLatch(3);
        WorkThread workThread1 = new WorkThread(1, 10, "  ", countDownLatch);
        WorkThread workThread2 = new WorkThread(2, 1, "  ", countDownLatch);
        WorkThread workThread3 = new WorkThread(3, 4, "  ", countDownLatch);
        workThread1.start();
        workThread2.start();
        workThread3.start();
        try {
            countDownLatch.await();
            System.out.println("All Thread Complete: ");
        } catch (InterruptedException e) {
            System.out.println("countDownLatch.await() Error");
        }
    }
}
class WorkThread extends Thread{
    private int index;
    private int time;
    private String name;
    private CountDownLatch countDownLatch;

    public WorkThread(int index, int time , String name, CountDownLatch countDownLatch) {
        this.index = index;
        this.time = time;
        this.name = name;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        System.out.println("Thread Index: " + index + ", Name: " + name + " Start");
        try {
            Thread.sleep(time * 1000);
        } catch (InterruptedException e) {
            System.out.println("Thread.sleep(2000) Error");
        }
        System.out.println("Thread Index: " + index + ", Name: " + name + " End");
        countDownLatch.countDown(); //   -1
    }
}

결과 출력:
1. 계수기 수치는 3

Thread Index: 1, Name:    Start
Thread Index: 2, Name:    Start
Thread Index: 3, Name:    Start
Thread Index: 2, Name:    End
Thread Index: 3, Name:    End
Thread Index: 1, Name:    End
All Thread Complete: 
           

2. 카운터 수치는 2

Thread Index: 1, Name:    Start
Thread Index: 2, Name:    Start
Thread Index: 3, Name:    Start
Thread Index: 2, Name:    End
Thread Index: 3, Name:    End
All Thread Complete: 
Thread Index: 1, Name:    End
           

3. 계수기의 수치는 4

Thread Index: 1, Name:    Start
Thread Index: 2, Name:    Start
Thread Index: 3, Name:    Start
Thread Index: 2, Name:    End
Thread Index: 3, Name:    End
Thread Index: 1, Name:    End
     

좋은 웹페이지 즐겨찾기