java 同步器的简单实用

倒计时门闩

倒计时门闩会导致一条或多条线程在“门口”一直等待,直到另一条线程打开着扇们,线程才能继续执行。它是由一个计数变量和两个操作数组成。这两个操作数分别是“导致一条线程等待直到计数变为0”以及“递减技术变量”。

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchDemo {
	
	public static void main(String[] args) throws Exception{
		int count = 5;
		CountDownLatch countDownLatch = new CountDownLatch(count);
		ExecutorService executorService = Executors.newFixedThreadPool(count);
		for (int i = 0; i < count; i++) {
			executorService.submit(() -> {
				try {
					Thread.sleep(3000L);
					System.out.println("Threand name:" + Thread.currentThread().getName());
					countDownLatch.countDown();
				} catch (Exception e) {
					e.printStackTrace();
				}
			});
		}
		
		countDownLatch.await();
		executorService.shutdown();
		System.out.println("shutdown");
	}
	
}

 

同步屏障

同步屏障允许一组线程彼此相互等待,直到抵达某个公共的循环点。因为该屏障在等待线程被释放之后可以重用,所以称它为可循环使用的屏障。该同步器对于数量固定并且互相之间必须不时等待彼此的多线程应用很有用。

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CyclicBarrierDemo {
	
	public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
		int count = 5;
		CyclicBarrier cyclicBarrier = new CyclicBarrier(count, () -> System.out.println("all done"));
		
		System.out.println(cyclicBarrier.getNumberWaiting());
		ExecutorService executorService = Executors.newFixedThreadPool(count);
		for (int i = 0; i < count; i++) {
			executorService.submit(() -> {
				try {
					Thread.sleep(3000L);
					System.out.println("name:" + Thread.currentThread().getName());
					cyclicBarrier.await();
				} catch (Exception e) {
					e.printStackTrace();
				}
			});
		}
		
		executorService.shutdown();
		System.out.println("done");
	}
	
}

 

交换器 

交换器提供了一个线程彼此之间能够交换对象的同步点。没条线程都在往这个交换器的exchange()方法传入一些对象,匹配伙伴线程,同时接受伙伴线程的对象作为返回值。

import java.util.concurrent.Exchanger;

public class ExchangerDemo {
	
	public static void main(String[] args) {
		Exchanger<String> exchanger = new Exchanger<>();
		new Thread(() -> {
			try {
				String result = exchanger.exchange("abc");
				System.out.println(Thread.currentThread().getName() + ":" + result);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}, "English").start();
		
		new Thread(() -> {
			try {
				String result = exchanger.exchange("123");
				System.out.println(Thread.currentThread().getName() + ":" + result);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}, "Number").start();
		
	}
	
}

 

信号量

信号量维护了一组许可证(permit),以约束被限制资源的线程数。当没有可用许可时,线程的获取尝试会一直阻塞,直到其他线程释放一个许可证。 

信号量和公平策略

当公平策略设置为false时,信号量不糊保证线程获取许可证的顺序。特别的,抢占是允许的。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreTest {
	
	public static void main(String[] args) {
		Semaphore semaphore = new Semaphore(10, true);
		System.out.println(semaphore.isFair());
		ExecutorService executorService = Executors.newFixedThreadPool(50);
		for (int i = 0; i < 50; i++) {
			executorService.submit(() -> {
				try {
					semaphore.acquire();
					System.out.println("name:" + Thread.currentThread().getName());
					Thread.sleep(2000L); // doing
					semaphore.release();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			});
		}
		
		executorService.shutdown();
	}
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

流年ln

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值