发布于 2018-01-01 05:56:53 | 185 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Java设计模式,程序狗速度看过来!

Java程序设计语言

java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由Sun Microsystems公司于1995年5月推出的Java程序设计语言和Java平台(即JavaEE(j2ee), JavaME(j2me), JavaSE(j2se))的总称。


本篇文章主要介绍了Java中多线程同步类 CountDownLatch的相关知识,具有很好的参考价值。下面跟着小编一起来看下吧

在多线程开发中,常常遇到希望一组线程完成之后在执行之后的操作,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

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持PHPERZ!



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务