`

java多线程 Semaphore CountDownLatch ScheduledExecutorService

阅读更多

参考:http://www.ibm.com/developerworks/cn/java/j-5things5.html

【关于 java.util.concurrent 您不知道的 5 件事,第 2 部分】

1,Semaphore

适用于:限制未处理的特定资源请求(线程/操作)数量。

public class SemApp {
    public static void main(String[] args) {
        Runnable limitedCall = new Runnable() {
            final Random rand = new Random();
            final Semaphore available = new Semaphore(3);
            int count = 0;
            public void run() {
                int time = rand.nextInt(15);
                int num = count++;
                try {
                    available.acquire();
                    System.out.println("Executing " + 
                        "long-running action for " + 
                        time + " seconds... #" + num);
                    Thread.sleep(time * 1000);
                    System.out.println("Done with #" + 
                        num + "!");
                    available.release();
                } catch (InterruptedException intEx) {
                    intEx.printStackTrace();
                }
            }
        };
        
        for (int i=0; i<10; i++)
            new Thread(limitedCall).start();
    }
}

 程序中实现了,限制了同时打开的任务数是三个。

结果 写道
Executing long-running action for 9 seconds... #0
Executing long-running action for 7 seconds... #2
Executing long-running action for 0 seconds... #1
Done with #1!
Executing long-running action for 1 seconds... #3
Done with #3!
Executing long-running action for 6 seconds... #4
Done with #2!
Executing long-running action for 5 seconds... #5
Done with #4!
Executing long-running action for 6 seconds... #6
Done with #0!
Executing long-running action for 12 seconds... #7
Done with #5!
Executing long-running action for 1 seconds... #8
Done with #8!
Executing long-running action for 12 seconds... #9
Done with #6!
Done with #7!
Done with #9!

 

对于特定资源和线程访问数的限定Semaphore是个不错的选择。这里使用了Semaphore一次使用和释放一个通行证,Semaphore还可以一次使用和释放多个通行证。

2,CountDownLatch

public class CDLApp {
	public static void main(String[] args)
	throws InterruptedException, java.io.IOException {
		System.out.println("Prepping...");
		Race r = new Race(
				"horse 1",	"horse 2",	"horse 3",	"horse 4",
				"horse 5",	"horse 6",	"horse 7",	"horse 8"
		);
		System.out.println("It's a race of " + r.getDistance() + " lengths");
		System.out.println("Press Enter to run the race....");
		System.in.read();
		r.run();
	}
}
class Race {
	private Random rand = new Random();
	private int distance = rand.nextInt(250);
	private List<String> horses = new ArrayList<String>();
	public Race(String... names) {
		this.horses.addAll(Arrays.asList(names));
	}
	public int getDistance() {return distance;}

	public void run() throws InterruptedException {
		System.out.println("And the horses are stepping up to the gate...");
		final CountDownLatch start = new CountDownLatch(1);
		final CountDownLatch finish = new CountDownLatch(horses.size());
		final List<String> places =
			Collections.synchronizedList(new ArrayList<String>());

		for (final String h : horses) {
			new Thread(new Runnable() {
				public void run() {
					try	{
						start.await();//等待赛马开始
						
						System.out.println(h + 
								" stepping up to the gate...");

						int traveled = 0;
						while (traveled < distance)	{
							//前进一次 暂停 0-2 秒
							Thread.sleep(rand.nextInt(3) * 1000);
							//前进 0-14 米
							traveled += rand.nextInt(15);
							System.out.println(h + 
									" advanced to " + traveled + "!");
						}
						System.out.println(h + 
						" crossed the finish!");
						places.add(h);
						
						finish.countDown();//一个马到达终点就 减去一, 倒数完成比赛结束
					}
					catch (InterruptedException intEx) {
						System.out.println("ABORTING RACE!!!");
						intEx.printStackTrace();
					}
				}
			}).start();
		}
		System.out.println("And... they're off!");
		start.countDown();//开始赛马

		finish.await();//等待所有的马跑完
		System.out.println("============================================");
		System.out.println("And we have our winners!");
		System.out.println("<"+places.get(0)+">" + " took the gold...");
		System.out.println("<"+places.get(1)+">" + " got the silver...");
		System.out.println("and " + "<"+places.get(2)+">" + " took home the bronze.");
		System.out.println("============================================");
	}
}

 

上面的程序利用CountDownLatch 描述一个赛马的过程,首先让所有马在门闩那里(start.countDown();//开始赛马)等待开始,每匹马冲过终点后(finish.countDown),finish.await()等待所有的马冲过终点后,发奖牌。

3,ScheduledExecutorService

public class Ping {
	public static void main(String[] args) {
        ScheduledExecutorService ses =
            Executors.newScheduledThreadPool(1);
        Runnable pinger = new Runnable() {
            public void run() {
                System.out.println("PING!");
            }
        };
        ses.scheduleAtFixedRate(pinger, 1, 2, TimeUnit.SECONDS);
    }
}

 

模拟心脏每隔2秒钟跳动一次。顺便说一下,如果用户希望取消心跳,scheduleAtFixedRate 调用将返回一个 ScheduledFuture 实例,它不仅封装了结果(如果有),还拥有一个 cancel 方法来关闭计划的操作。

 

分享到:
评论

相关推荐

    Java多线程Semaphore工具的使用详解.rar

    Java多线程Semaphore工具的使用详解.rar

    java线程并发semaphore类示例

    Java 5.0里新加了4个协调线程间进程的同步装置,它们分别是Semaphore, CountDownLatch, CyclicBarrier和Exchanger,本例主要介绍Semaphore,Semaphore是用来管理一个资源池的工具,可以看成是个通行证

    java并发工具类(CountDownLatch+Semaphore+Exchanger)

    java并发工具类(CountDownLatch+Semaphore+Exchanger);java并发工具类(CountDownLatch+Semaphore+Exchanger);java并发工具类(CountDownLatch+Semaphore+Exchanger);java并发工具类(CountDownLatch+...

    Java并发编程一CountDownLatch、CyclicBarrier、Semaphore初使用

    CountDownLatch可以实现一个线程等待多个线程、多个线程等待一个线程、多个线程等待多个线程(这里不涉及)。 我们首先来看看怎么实现一个线程等待多个线程吧。 工厂中,对产品需要进行质检,5个工人进行检查,所有...

    JAVA多线程--信号量(Semaphore)_.docx

    JAVA多线程--信号量(Semaphore)_.docx

    个人总结的深入java多线程开发

    看完《think in java》多线程章节,自己写的多线程文档,还结合了其他的相关网络资料。 线程 一. 线程池 1)为什么要使用线程池 2 2)一个具有线程池的工作队列 3 3)使用线程池的风险: 4 4)有效使用线程池的原则 5...

    Java多线程之并发工具类

     1)CountDownLatch(同步倒数计数器:等待多线程(或者多步骤)完成)  2)CyclicBarrier(循环屏障:同步屏障)  3)Semaphore(信号量:控制并发进程数)  主要参考资料:java并发编程的艺术、Java并发——...

    2023年最新Java高并发多线程面试题

    内容概要:最新2023年Java高并发多线程后端面试题整理, 包含线程池,并发集合,volatile,CountDownLatch,Semaphore,Phaser,AQS,ReentrantLock,ReentrantLock等等问题, 用简洁明了的语言,通俗易懂地阐述了高...

    java并发之Semaphore信号量.md

    Semaphore是计数信号量。Semaphore管理一系列许可证。每个acquire方法阻塞,直到有一个许可证可以获得然后拿走一个许可证;每个release方法增加一个许可证,这可能会释放一个阻塞的acquire方法。然而,其实并没有...

    详解java多线程的同步控制

    目录线程安全 Thread Safety重入锁 ReentrantLock读写锁 ReadWriteLock倒计数器 CountDownLatch循环栅栏 CyclicBarrier信号量 Semaphore 线程安全 Thread Safety JMM JMM(Java Memory Model)是一种基于计算机内存...

    JAVA 多线程之信号量(Semaphore)实例详解

    主要介绍了JAVA 多线程之信号量(Semaphore)实例详解的相关资料,需要的朋友可以参考下

    python多线程semaphore实现线程数控制的示例

    主要介绍了python多线程semaphore实现线程数控制的示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

    92道Java多线程与并发面试题含答案(很全)

    Java并发编程的核心概念包括: 线程(Thread):线程是程序执行流的最小单元。...原子操作(Atomic Operations):原子操作是不可中断的操作,即在多线程环境中,这些操作要么完全执行,要么完全不执行。

    多线程(C++)同步Semaphore

    多线程(C++)同步Semaphore

    Java并发编程:CountDownLatch与CyclicBarrier和Semaphore的实例详解

    主要介绍了Java并发编程:CountDownLatch与CyclicBarrier和Semaphore的实例详解的相关资料,需要的朋友可以参考下

    semaphore控制多线程循序执行

    semaphore控制多线程循序执行,网上 找的例子更改的希望对大家有用

    Delphi多线程之Semaphore_(信号对象).pdf

    Delphi多线程之Semaphore_(信号对象).pdf

    Java中的Semaphore类最全讲义

    1.2 Semaphore概述 Semaphore的基本用法 2.1 创建Semaphore对象 2.2 acquire()方法 2.3 release()方法 控制资源访问数量 3.1 场景介绍 3.2 使用Semaphore控制资源访问 实现有界资源池 4.1 场景介绍 4.2 使用...

    java并发核心Semaphore 的使用思路.docx

    Semaphore 是 synchronized 的加强版,作用是控制线程的并发数量。就这一点而言,单纯的synchronized 关键字是实现不了的。 直接看例子吧,这个例子包含3个类,一个是线程类,一个是 Semaphore 关键代码类,一个类是...

Global site tag (gtag.js) - Google Analytics