gpt4 book ai didi

Java中多线程同步类 CountDownLatch

转载 作者:qq735679552 更新时间:2022-09-27 22:32:09 26 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章Java中多线程同步类 CountDownLatch由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

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

类中常见的方法:

Java中多线程同步类 CountDownLatch

其中构造方法:

CountDownLatch(int count) 参数count是计数器,一般用要执行线程的数量来赋值.

long getCount():获得当前计数器的值.

void countDown():当计数器的值大于零时,调用方法,计数器的数值减少1,当计数器等数零时,释放所有的线程.

void await():调所该方法阻塞当前主线程,直到计数器减少为零.

代码例子:

线程类:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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();
  }
 
}
 
}

测试类:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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();
  }
  }
}

输出结果:

?
1
2
3
4
5
6
7
8
9
10
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.cnblogs.com/ITer-jack/p/6791803.html 。

最后此篇关于Java中多线程同步类 CountDownLatch的文章就讲到这里了,如果你想了解更多关于Java中多线程同步类 CountDownLatch的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com