`
DavyJones2010
  • 浏览: 153823 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Java SE: Concurrency Utils DelayQueue

阅读更多

1) DelayQueue class implements the BlockingQueue interface.

    The DelayQueue keeps the elements internally until a certain delay has expired.

    The elements must implement the interface java.util.concurrent.Delayed.

public interface Delayed extends Comparable<Delayed> {
    long getDelay(TimeUnit unit);
}

    The value returned by the getDelay() method should be the delay remaining before this element can be released.

    If 0 or a negative value is returned, the delay will be considered expired, and the element released at the next take() etc. call on the DelayQueue.

    The TimeUnit instance passed to the getDelay() method is an Enum that tells which time unit the delay should be returned in.

    The TimeUnit enum can take these values:

DAYS
HOURS
MINUTES
SECONDS
MILLISECONDS
MICROSECONDS
NANOSECONDS

    The Delayed Interface also extends the java.lang.Comparable interface, as you can see, which means that Delayed objects can be compared to each other.

    This is probably  used internally in the DelayQueue to order the elements in the queue, so they are released ordered by their expiration time.

    Example For DelayQueue:

package edu.xmu.thread;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayQueueTest {
	public static void main(String[] args) throws InterruptedException {
		Delayed delayedElement = new DelayedElement(10);
		System.out.println(delayedElement.getDelay(TimeUnit.MICROSECONDS));
		DelayQueue<Delayed> delayQueue = new DelayQueue<Delayed>();
		delayQueue.add(delayedElement);
		System.out.println(System.currentTimeMillis());
		Delayed delayedElement2 = delayQueue.take();
		System.out.println("delayedElement2: " + delayedElement2);
		System.out.println(System.currentTimeMillis());
	}
}

class DelayedElement implements Delayed {
	long endTime;

	public DelayedElement(int delaySeconds) {
		super();
		this.endTime = TimeUnit.NANOSECONDS.convert(delaySeconds,
				TimeUnit.SECONDS) + System.nanoTime();
	}

	@Override
	public int compareTo(Delayed o) {
		return 0;
	}

	@Override
	public long getDelay(TimeUnit unit) {
		return unit.convert(endTime - System.nanoTime(), TimeUnit.NANOSECONDS);
	}

}

    Output:

9999989
1401202204613
delayedElement2: edu.xmu.thread.DelayedElement@af07c4
1401202214613

 

2) SynchronousQueue

    1> The SynchronousQueue class implements the BlockingQueue interface.

    2> The SynchronousQueue is a queue that can only contain a single element internally.

         A thread inserting an element into the queue in blocked until another thread takes that element from the queue.

         Likewise, if a thread tries to take an element and no element is currently present, that thread is blocked util a thread insert an element into the queue.

         Calling this class a queue is a bit of an overstatement. It's more of a rendesvouz point.

package edu.xmu.thread;

import java.util.concurrent.SynchronousQueue;

public class SynchronousQueueTest {
	public static void main(String[] args) {
		SynchronousQueue<SynchronousData> synchronousQueue = new SynchronousQueue<SynchronousData>();
		Thread producer = new Thread(new SynchronousProducerThread(
				synchronousQueue));
		Thread producer2 = new Thread(new SynchronousProducerThread(
				synchronousQueue));

		Thread consumer = new Thread(new SynchronousConsumerThread(
				synchronousQueue));
		Thread consumer2 = new Thread(new SynchronousConsumerThread(
				synchronousQueue));

		consumer.start();
		consumer2.start();

		producer.start();
		producer2.start();
	}
}

class SynchronousProducerThread implements Runnable {
	SynchronousQueue<SynchronousData> synchronousQueue;

	public SynchronousProducerThread(
			SynchronousQueue<SynchronousData> synchronousQueue) {
		super();
		this.synchronousQueue = synchronousQueue;
	}

	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep((long) (Math.random() * 1000));

				System.out.println("Thread: " + Thread.currentThread()
						+ " is trying to put synchronousQueue");

				SynchronousData synchronousData = new SynchronousData();
				synchronousQueue.put(synchronousData);

				System.out.println("Thread: " + Thread.currentThread()
						+ " put synchronousData: " + synchronousData);

			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}

class SynchronousConsumerThread implements Runnable {
	SynchronousQueue<SynchronousData> synchronousQueue;

	public SynchronousConsumerThread(
			SynchronousQueue<SynchronousData> synchronousQueue) {
		super();
		this.synchronousQueue = synchronousQueue;
	}

	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep((long) (Math.random() * 1000));

				System.out.println("Thread: " + Thread.currentThread()
						+ " is trying to take from synchronousQueue");

				SynchronousData synchronousData = synchronousQueue.take();

				System.out.println("Thread: " + Thread.currentThread()
						+ " got synchronousData: " + synchronousData);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}

class SynchronousData {
}

 

 

Reference Links:

1) http://tutorials.jenkov.com/java-util-concurrent/delayqueue.html

2) http://tutorials.jenkov.com/java-util-concurrent/synchronousqueue.html

 

分享到:
评论

相关推荐

    Reactive Streams in Java: Concurrency with RxJava, Reactor, and Akka Streams

    Get an easy introduction to reactive streams in Java to handle concurrency, data streams, and the propagation of change in today's applications. This compact book includes in-depth introductions to ...

    Java Lesson: Concurrency

    Java并发编程是Java平台的核心特性之一,它使得开发者可以创建能够充分利用多核处理器能力的高效应用程序。本课程将深入探讨Java中的并发概念,包括基础支持和高阶API,特别是`java.util.concurrent`包中的工具。 ...

    Reactive Streams in Java.pdf

    Reactive Streams in Java Concurrency with RxJava, Reactor, and Akka Streams. 2019年最新出版,清晰文字PDF,带目录书签。

    Transactions: Concurrency Control and Recovery: Optimist concurrency control

    其中,乐观并发控制(Optimistic Concurrency Control, OCC)是一种不同于传统的基于锁的并发控制机制的方法。 #### 乐观并发控制简介 乐观并发控制作为一种对传统两阶段锁定(2PL)方法的反应而出现。两阶段锁定...

    Transactions: Concurrency Control and Recovery

    - **实现方法**:常见的并发控制技术包括锁机制(Lock-based)、乐观并发控制(Optimistic Concurrency Control, OCC)、多版本并发控制(Multiversion Concurrency Control, MVCC)等。 - **恢复**: - **定义**...

    Swift异步编程指南:Concurrency与高级技巧

    内容概要:本文介绍了 Swift 语言的异步编程基础及其 Concurrency 框架的重要特性。主要内容涵盖异步编程的基础理论模型、基于async/await和 DispatchQueues的技术实现、异步任务与并发对象管理(Task 和 Actor 模型)...

    Java.Threads.and.the.Concurrency.Utilities.1484216997

    This concise book empowers all Java developers to master the complexity of the Java thread APIs and concurrency utilities. This knowledge aids the Java developer in writing correct and complex ...

    Concurrency by Tutorials.zip

    Raywenderlich: Concurrency by Tutorials Raywenderlich: Concurrency by Tutorials Raywenderlich: Concurrency by Tutorials

    Java.7.A.Comprehensive.Tutorial

    Chapter 24 Concurrency Utilities Chapter 25 Security Chapter 26 Java Web Applications Chapter 27 JavaServer Pages Chapter 28 Javadoc Chapter 29 Application Deployment Chapter 30 Reflection Chapter 31 ...

    Java Concurrency in Practice JAVA并发编程实践(中英文版)

    Using the concurrency building blocks in java.util.concurrent Performance optimization dos and don'ts Testing concurrent programs Advanced topics such as atomic variables, nonblocking algorithms, ...

    Java并发编程实践(java concurrency in practice)pdf (java多线程总结.ppt)

    《Java并发编程实践》是Java开发者必读的经典之作,由Brian Goetz等多位专家共同撰写。这本书深入浅出地探讨了Java平台上的并发问题,帮助读者理解和掌握如何编写高效、可靠且可维护的多线程应用程序。以下是该书...

    Java Concurrency in Practice 无水印pdf

    Java Concurrency in Practice 英文无水印pdf pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者...

    Java SE 8 for the Really Impatient

    Eagerly anticipated by millions of programmers, Java SE 8 is the most important Java update in many years. The addition of lambda expressions (closures) and streams represents the biggest change to ...

    《Java 7 Concurrency Cookbook》英文

    《Java 7 Concurrency Cookbook》教程及代码。 《Java 7 Concurrency Cookbook》这本书不错,每节一个实例。 《Java Concurrency in Practice》这本书理论比较多,有点难懂,适合高级水平吧。 Book review: ...

    Java 9 Concurrency Cookbook - Second Edition

    Java 9 Concurrency Cookbook - Second Edition by Javier Fernandez Gonzalez English | 25 Apr. 2017 | ASIN: B01KOG6V5M | 594 Pages | AZW3 | 4.11 MB Key Features Get detailed coverage of important ...

    java并行编程(Java Concurrency in Practice) 英文版chm

    &lt;&lt;java并行编程&gt;&gt;英文版chm格式,英文名称&lt;Java Concurrency in Practice&gt;,一直想买这本书,但总是缺货,找到了电子版,分享给大家。 Java Concurrency in Practice By Brian Goetz, Tim Peierls, Joshua Bloch,...

    Java-concurrency-master.zip

    `Java-concurrency-master.zip`这个压缩包很可能包含了关于Java并发编程的各种资料和示例,对于学习和理解Java并发机制非常有帮助。 Java并发主要包括以下几个核心知识点: 1. **线程**:Java通过`Thread`类来创建...

Global site tag (gtag.js) - Google Analytics