Java并发编程之闭锁与栅栏的实现

2022-10-07,,,,

一、前言

闭锁栅栏是在多线程编程中的概念,因为在多线程中,我们不能控制线程的执行状态,所以给线程加锁,让其按照我们的想法有秩序的执行。

闭锁

countdownlatch,实例化时需要传入一个int类型的数字(count),意为等待count个线程完成之后才能执行下一步动作。

如今天要做的事情是吃晚饭,再去散步。假设11个人相约晚饭后一起去散步,我们得等11个人全都吃完晚饭了才能出发去散步。简而言之就是做了才到达某一种状态。

栅栏

cyclicbarrier,实例化时需要传入一个int类型的数字(parties),意为等待parties个线程都准备就绪后才能执行自己的任务。

如今天要做的事情是吃晚饭,8个人约好一起去某餐厅吃饭,得等到人齐了才能去吃饭。简而言之就是到达某种状态后一起做。

二、实例

闭锁 countdownlatch

package com.test;
 
import java.util.arraylist;
import java.util.list;
import java.util.concurrent.brokenbarrierexception;
import java.util.concurrent.countdownlatch;
 
public class test {
 public static void main(string[] args) {
 countdownlatch latch = new countdownlatch(3);
 
        // 模拟三个任务
 list<string> jobs = new arraylist<string>();
 jobs.add("first");
 jobs.add("second");
 jobs.add("third");
    
        // 循环执行任务
 for (string job : jobs) {
  new thread(new runnable() {
 
  @override
  public void run() {
   system.out.println(thread.currentthread().getname() + " : 进入run方法");
   latch.countdown();
   system.out.println(thread.currentthread().getname() + " : 执行" + job);
  }
  }).start();
 }
 
 try {
  latch.await();
 } catch (interruptedexception e) {
  e.printstacktrace();
 }
 // 任务都执行完后才执行
 system.out.println("回到main线程");
 }
 
}

执行结果:

thread-1 : 进入run方法

thread-2 : 进入run方法

thread-2 : 执行third

thread-0 : 进入run方法

thread-1 : 执行second

thread-0 : 执行first

回到main线程

通过执行结果可看出,当所有线程都执行完后才能回到主线程继续执行后面的输出。

栅栏 cyclicbarrier

package com.test;
 
import java.util.arraylist;
import java.util.list;
import java.util.concurrent.brokenbarrierexception;
import java.util.concurrent.cyclicbarrier;
 
public class test {
 public static void main(string[] args) {
 cyclicbarrier barrier = new cyclicbarrier(3);
 // 模拟创建三个任务
 list<string> jobs = new arraylist<string>();
 jobs.add("first");
 jobs.add("second");
 jobs.add("third");
 //循环执行任务
 for (string job : jobs) {
  new thread(new runnable() {
 
  @override
  public void run() {
   system.out.println(thread.currentthread().getname() + " : 进入run方法");
   try {
   // 等待
   barrier.await();
   } catch (interruptedexception | brokenbarrierexception e) {
   e.printstacktrace();
   }
   system.out.println(thread.currentthread().getname() + " : 执行" + job);
  }
  }).start();
 }
 } 
}

执行结果:

thread-1 : 进入run方法

thread-2 : 进入run方法

thread-0 : 进入run方法

thread-0 : 执行first

thread-1 : 执行second

thread-2 : 执行third

通过执行结果可看出,当所有线程都执行都进入到run方法后,才能继续执行自己内部的方法。

到此这篇关于java并发编程之闭锁与栅栏的实现的文章就介绍到这了,更多相关java 闭锁与栅栏内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《Java并发编程之闭锁与栅栏的实现.doc》

下载本文的Word格式文档,以方便收藏与打印。