Java多线程之同步工具类

来源:互联网 发布:蚁群算法和粒子群算法 编辑:程序博客网 时间:2024/06/02 19:43

Java多线程之同步工具类

    闭锁是一种同步工具类,可以延迟线程的进度直到其到达终止状态。闭锁的作用相当于一扇门,在闭锁到达结束状态之前,这扇门一直是关闭的并且没有任何线程可以通过,当到达结束状态时,这扇门会打开,并且允许所有的线程通过。当闭锁到达结束状态时,将不会再改变状态,因此这扇门将永远保持打开。闭锁可以确保某一线程直到其他线程结束才结束。

    CountDownLatch是一种灵活的闭锁实现。他可以是一个或一组线程等待一组事件的发生。闭锁的状态包括一个计数器,该计数器初始化为一个正数,表示需要等待的事件的数量,countDown方法递减计数器,表示有一个事件已经发生。如果计数器非零,那么await方法会一直阻塞直到计数器为零,或者等待中的线程中断或者超时。

  实例程序:该程序模拟连续数字累加计算,主线程开启两个线程,分别计算部分运算,最后主线程将处理子线程的部分结果,最终得到最终的结果。


import java.util.concurrent.CountDownLatch;


public class CountDownLatchTest {

public static void main(String[] args) throws InterruptedException{
final int THREADCNT = 2;
int[] result = new int[THREADCNT];
CountDownLatch latch = new CountDownLatch(THREADCNT);
new Thread(new WorkerThread(0, 0, 50, latch, result)).start();
new Thread(new WorkerThread(1, 50, 100, latch, result)).start();
latch.await();
int total = 0;
for(int t=0; t<THREADCNT; ++t){
total += result[t];
}
System.out.println("the result is: " + total);
}

static class WorkerThread implements Runnable{

private int index;

private int begin;

private int end;

private int[] result;

private CountDownLatch latch;

public WorkerThread(int index, int begin, int end, CountDownLatch latch, int[] result){
this.index = index;
this.begin = begin;
this.end = end;
this.latch = latch;
this.result = result;
}


public void run() {
int total = 0;
for(int t=begin; t<end; ++t){
total += t;
}
result[index] = total;
latch.countDown();
}
}


}


0 0