Java queue Queue

A queue is a special kind of linear table that only allows delete operations at the front end of the table and insert operations at the back end of the table. The end that performs the insert operation is called the tail of the queue, and the end that performs the delete operation is called the head of the queue. When there are no elements in the queue, it is called an empty queue.
In the data structure of the queue, the first element inserted will be the first deleted element; otherwise, the last inserted element will be the last deleted element, so the queue is also called "first in, first out" (FIFO—first in first out) linear table.

     throw an exception and return a special value
insert add(e) offer(e)
remove remove() poll()
Check element() peek()


When using Queue, try to avoid the add() and remove() methods of Collection, but use offer() to add elements, and use poll() to get and remove elements. Their advantage is that success or failure can be judged by the return value,
The add() and remove() methods throw exceptions when they fail. To use the front end without removing the element, use the element() or peek() methods.
The element method throws an exception when the queue is empty, while peek returns null.

The LinkedList class implements the Queue interface

public class QueueTest {
	public static void main(String[] args) {
		// add() and remove() methods will throw exceptions when they fail (not recommended)
		Queue<String> queue = new LinkedList<String>();
		// add element
		queue.offer("a");
		queue.offer("b");
		queue.offer("c");
		queue.offer("d");
		queue.offer("e");
		for (String q : queue) {
			System.out.println(q);
		}
		System.out.println("===");
		System.out.println("poll=" + queue.poll()); // return the first element and delete it from the queue
		for (String q : queue) {
			System.out.println(q);
		}
		System.out.println("===");
		System.out.println("element=" + queue.element()); // returns the first element
		for (String q : queue) {
			System.out.println(q);
		}
		System.out.println("===");
		System.out.println("peek=" + queue.peek()); // return the first element
		for (String q : queue) {
			System.out.println(q);
		}
	}
}

BlockingQueue is a blocking queue. As can be seen from the word blocking, access to the blocking queue may cause blocking in some cases. There are two main types of blocking:

1. When the queue is full, enter the queue operation
2. When the queue is empty, perform the dequeue operation

BlockingQueue has four interfaces, and the methods defined by the interfaces are as follows:
Throws Exception	Special Value	Blocks	Times Out
插入	add(o)		offer(o)	put(o)	offer(o, timeout, timeunit)
移除	remove(o)	poll()		take()	poll(timeout, timeunit)
Check element() peek()		

The corresponding characteristics of these four methods are:

The BlockingQueue method comes in four forms,

For operations that cannot be satisfied immediately but may be satisfied at some point in the future,
The four forms are handled differently: the first is to throw an exception,
The second is to return a special value (null or false, depending on the operation),
The third is to block the current thread indefinitely until the operation can succeed,
The fourth is to block only for a given maximum time limit before giving up


Implementation class of BlockingQueue

1. ArrayBlockingQueue
2.DelayQueue
3. LinkedBlockingQueue
4.PriorityBlockingQueue
5. SynchronousQueue



ArrayBlockingQueue is a bounded blocking queue whose internal implementation is an array. Bounded means that its capacity is limited, we must specify its capacity size when it is initialized, and once the capacity size is specified, it cannot be changed.

The configuration of the size of the LinkedBlockingQueue blocking queue is optional. If we specify a size during initialization, it is bounded. If we do not specify it, it is unbounded. Said to be unbounded, in fact, the default size is Integer.MAX_VALUE capacity
Its internal implementation is a linked list.

PriorityBlockingQueue is an unbounded queue with the same ordering rules as java.util.PriorityQueue. It should be noted that null objects are allowed to be inserted into the PriorityBlockingQueue.
All objects inserted into PriorityBlockingQueue must implement the java.lang.Comparable interface, and the sorting rules of queue priorities are defined according to our implementation of this interface.

Only one element is allowed inside the SynchronousQueue queue. When a thread inserts an element it will block unless the element is consumed by another thread.

DelayQueue
It is an unbounded BlockingQueue that is used to place objects that implement the Delayed interface, in which objects can only be taken from the queue when they expire. This queue is ordered,
That is, the delay expiration time of the head of queue object is the longest. If no delay expires, then there will be no header elements and poll will return null (and because of this, cannot
null is placed in this queue).


DelayQueue blocks its internal elements. The elements in DelayQueue must implement the java.util.concurrent.Delayed interface. The definition of this interface is very simple:
public interface Delayed extends Comparable<Delayed> {
	long getDelay(TimeUnit unit);
}

The return value of the getDelay() method is the holding time before the queue element is released. If it returns 0 or a negative value, it means that the element has expired and needs to be released. At this time, DelayedQueue will release the object through its take() method. .
As can be seen from the definition of the Delayed interface above, it also inherits the Comparable interface, because the elements in the DelayedQueue need to be sorted. In general, we sort by the priority of the expiration time of the elements.

PriorityBlockingQueue example:
public class PriorityElement implements Comparable<PriorityElement> {
	private int priority;// define the priority
	PriorityElement(int priority) {
		// initialize priority
		this.priority = priority;
	}
	@Override
	public int compareTo(PriorityElement o) {
		// sort by priority size
		return priority >= o.getPriority() ? 1 : -1;
	}
	public int getPriority() {
		return priority;
	}
	public void setPriority(int priority) {
		this.priority = priority;
	}
	@Override
	public String toString() {
		return "PriorityElement [priority=" + priority + "]";
	}
}

public class PriorityBlockingQueueExample {
	public static void main(String[] args) throws InterruptedException {
	    PriorityBlockingQueue<PriorityElement> queue = new PriorityBlockingQueue<PriorityElement>();
	    for (int i = 0; i < 5; i++) {
	        Random random=new Random();
	        PriorityElement ele = new PriorityElement(random.nextInt(10));
	        queue.put(it);
	    }
	    while(!queue.isEmpty()){
	        System.out.println(queue.take());
	    }
	}
}


Reference article: http://blog.csdn.net/suifeng3051/article/details/48807423

PipeStream is a special kind of stream used to transfer data between different threads, one thread sends data to the pipe at one end, and the other thread reads from the input pipe
There are two types of pipeline flows:
Character stream: PipedReader, PipedWriter
Byte stream: PipedInputStrean, PipedOutputStram

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

public class PipedWriteTest {

	public static class ThradPipedReaderA extends Thread {
		PipedReader pipedReader;
		public ThradPipedReaderA(PipedReader pipedReader) {
			this.pipedReader = pipedReader;
		}
		@Override
		public void run() {
			try {
				char [] chararray = new char [20];
				int readLenth = pipedReader.read(chararray);
				while (readLenth != -1) {
					String str = new String(chararray, 0, readLenth);
					System.out.println("The read data is: " + str);
					readLenth = pipedReader.read(chararray);
				}
				pipedReader.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace ();
			}
		}
	}
	public static class ThradPipedWriteB extends Thread {
		PipedWriter pipedWriter;
		public ThradPipedWriteB(PipedWriter pipedWriter) {
			this.pipedWriter = pipedWriter;
		}
		@Override
		public void run() {
			try {
				for (int i = 0; i <= 10; i++) {
					pipedWriter.write("Send data" + i);
				}
				pipedWriter.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace ();
			}
		}
	}
	public static void main(String[] args) throws IOException {
		PipedReader pipedReader = new PipedReader();
		PipedWriter pipedWriter = new PipedWriter();
		pipedReader.connect(pipedWriter);// Make a link to communicate
		ThradPipedReaderA a = new ThradPipedReaderA(pipedReader);
		ThradPipedWriteB b = new ThradPipedWriteB(pipedWriter);
		a.start();
		b.start();
	}
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326227479&siteId=291194637