手机版
你好,游客 登录 注册
背景:
阅读新闻

Java中多线程同步类 CountDownLatch

[日期:2017-05-02] 来源:Linux社区  作者:ITer-jack [字体: ]

在多线程开发中,常常遇到希望一组线程完成之后在执行之后的操作,Java提供了一个多线程同步辅助类,可以完成此类需求:
类中常见的方法:



其中构造方法:CountDownLatch(int count) 参数count是计数器,一般用要执行线程的数量来赋值。
long getCount():获得当前计数器的值。
void countDown():当计数器的值大于零时,调用方法,计数器的数值减少1,当计数器等数零时,释放所有的线程。
void await():调所该方法阻塞当前主线程,直到计数器减少为零。
代码例子:
线程类:

import java.util.concurrent.CountDownLatch;
public class TestThread extends Thread{
CountDownLatch cd;
String threadName;
public TestThread(CountDownLatch cd,String threadName){
    this.cd=cd;
    this.threadName=threadName;
    
}
@Override
public void run() {
    System.out.println(threadName+" start working...");
    dowork();
    System.out.println(threadName+" end working and exit...");
    cd.countDown();//告诉同步类完成一个线程操作完成
    
}
private void dowork(){
    try {
        Thread.sleep(2000);
        System.out.println(threadName+" is working...");
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    
}

}

测试类:

import java.util.concurrent.CountDownLatch;
public class TsetCountDownLatch {

    public static void main(String[] args) {
        try {
            CountDownLatch cd = new CountDownLatch(3);// 表示一共有三个线程
            TestThread thread1 = new TestThread(cd, "thread1");
            TestThread thread2 = new TestThread(cd, "thread2");
            TestThread thread3 = new TestThread(cd, "thread3");
            thread1.start();
            thread2.start();
            thread3.start();
            cd.await();//等待所有线程完成
            System.out.println("All Thread finishd");
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

输出结果:

    thread1 start working...
    thread2 start working...
    thread3 start working...
    thread2 is working...
    thread2 end working and exit...
    thread1 is working...
    thread3 is working...
    thread3 end working and exit...
    thread1 end working and exit...
    All Thread finishd

本文永久更新链接地址http://www.linuxidc.com/Linux/2017-05/143335.htm

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款