📜  Java中的 TransferQueue 接口

📅  最后修改于: 2022-05-13 01:55:06.859000             🧑  作者: Mango

Java中的 TransferQueue 接口

TransferQueue接口是Java集合框架的成员。它是在 JDK 1.7 中引入的,它属于Java.util.concurrent包。 TransferQueue 是一个 BlockingQueue,其中发送线程(生产者)可以等待接收线程(消费者)接收元素。 TransferQueue 用于消息传递应用程序。消息从生产者线程传递到消费者线程有两个方面。

  • put(E e) :如果生产者希望在不等待消费者的情况下将元素加入队列,则使用此方法。但是,如果队列已满,它会等待空间变为可用。
  • transfer(E e) : 该方法一般用于将一个元素传递给一个正在等待接收它的线程,如果没有线程在等待,那么它会一直等待,直到等待线程一到就进入等待状态元素将被转移到其中。

还可以通过hasWaitingConsumer()查询 TransferQueue 是否有任何线程在等待项目,这与 peek 操作相反。

宣言

public interface TransferQueue extends BlockingQueue

这里, E是存储在集合中的元素类型。

TransferQueue 的层次结构

Java 中传输队列的层次结构

它扩展了 BlockingQueueCollectionIterable 、Queue 接口。

例子:

Java
// Java Program Demonstrate TransferQueue
  
import java.util.concurrent.*;
import java.util.*;
  
public class TransferQueueDemo {
    public static void main(String[] args)
        throws InterruptedException
    {
        // create object of TransferQueue
        // using LinkedTransferQueue() constructor
        TransferQueue TQ
            = new LinkedTransferQueue();
  
        // Add numbers to end of queue
        TQ.add(7855642);
        TQ.add(35658786);
        TQ.add(5278367);
        TQ.add(74381793);
  
        // print Queue
        System.out.println("Queue1: " + TQ);
  
        // create object of TransferQueue
        // using LinkedTransferQueue(Collection c)
        // constructor
        TransferQueue TQ2
            = new LinkedTransferQueue(TQ);
  
        // print Queue
        System.out.println("Queue2: " + TQ2);
    }
}


Java
// Java Program Demonstrate adding
// elements to TransferQueue
  
import java.util.concurrent.*;
  
class AddingElementsExample {
    public static void main(String[] args) throws Exception
    { 
  
        // Initializing the queue
        TransferQueue queue
            = new LinkedTransferQueue();
  
        // Adding elements to this queue
        for (int i = 10; i <= 14; i++)
            queue.add(i);
  
        // Add the element using offer() method
        System.out.println("adding 15 "
            + queue.offer(15, 5, TimeUnit.SECONDS));
  
        // Adding elements to this queue
        for (int i = 16; i <= 20; i++)
            queue.put(i);
  
        // Printing the elements of the queue
        System.out.println(
            "The elements in the queue are:");
        for (Integer i : queue)
            System.out.print(i + " ");
  
        System.out.println();
  
        // create another queue to demonstrate transfer
        // method
        TransferQueue g
            = new LinkedTransferQueue();
  
        new Thread(new Runnable() {
            public void run()
            {
                try {
                    System.out.println("Transferring"
                                       + " an element");
  
                    // Transfer a String element
                    // using transfer() method
                    g.transfer("is a computer"
                               + " science portal.");
                    System.out.println(
                        "Element "
                        + "transfer is complete");
                }
                catch (InterruptedException e1) {
                    System.out.println(e1);
                }
                catch (NullPointerException e2) {
                    System.out.println(e2);
                }
            }
        })
            .start();
  
        try {
  
            // Get the transferred element
            System.out.println("Geeks for Geeks "
                               + g.take());
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}


Java
// Java Program Demonstrate removing
// elements of TransferQueue
  
import java.util.concurrent.*;
  
class RemoveElementsExample {
    public static void main(String[] args)
    {
        // Initializing the queue
        TransferQueue queue
            = new LinkedTransferQueue();
  
        // Adding elements to this queue
        for (int i = 1; i <= 5; i++)
            queue.add(i);
  
        // Printing the elements of the queue
        System.out.println(
            "The elements in the queue are:");
        for (Integer i : queue)
            System.out.print(i + " ");
  
        // remove() method will remove the specified
        // element from the queue
        queue.remove(1);
        queue.remove(5);
  
        // Printing the elements of the queue
        System.out.println("\nRemaining elements in queue : ");
        for (Integer i : queue)
            System.out.print(i + " ");
    }
}


Java
// Java Program Demonstrate 
// iterating over TransferQueue
  
import java.util.Iterator;
import java.util.concurrent.*;
  
class IteratingExample {
    public static void main(String[] args)
    {
  
        // Initializing the queue
        TransferQueue queue
            = new LinkedTransferQueue();
  
        // Adding elements to this queue
        queue.add("Gfg");
        queue.add("is");
        queue.add("fun!!");
  
        // Returns an iterator over the elements
        Iterator iterator = queue.iterator();
  
        // Printing the elements of the queue
        while (iterator.hasNext())
            System.out.print(iterator.next() + " ");
    }
}


输出
Queue1: [7855642, 35658786, 5278367, 74381793]
Queue2: [7855642, 35658786, 5278367, 74381793]

实现类

TransferQueue 有一个实现类,它是 LinkedTransferQueue。 LinkedTransferQueue是基于链接节点的 TransferQueue 接口的无界实现。 LinkedTransferQueue 中的元素按先进先出的顺序排列,头部指向在队列中停留时间最长的元素,尾部指向在队列中停留时间最短的元素。

由于其异步性质,size() 遍历整个集合,因此它不是 O(1) 时间操作。如果在遍历期间修改此集合,它也可能给出不准确的大小。 addAll、removeAll、retainAll、containsAll、equals 和 toArray 等批量操作不能保证以原子方式执行。例如,与 addAll 操作同时运行的迭代器可能只观察到一些添加的元素。

句法:

TransferQueue objectName = new LinkedTransferQueue();

基本操作

1. 添加元素

LinkedTransferQueue 提供了各种方法的实现来添加或插入元素。它们是add(E e)put(E e)offer(E e)transfer(E e) 。 add、put 和 offer 方法在 transfer() 等待一个或多个接收线程时不关心其他线程是否访问队列。

Java

// Java Program Demonstrate adding
// elements to TransferQueue
  
import java.util.concurrent.*;
  
class AddingElementsExample {
    public static void main(String[] args) throws Exception
    { 
  
        // Initializing the queue
        TransferQueue queue
            = new LinkedTransferQueue();
  
        // Adding elements to this queue
        for (int i = 10; i <= 14; i++)
            queue.add(i);
  
        // Add the element using offer() method
        System.out.println("adding 15 "
            + queue.offer(15, 5, TimeUnit.SECONDS));
  
        // Adding elements to this queue
        for (int i = 16; i <= 20; i++)
            queue.put(i);
  
        // Printing the elements of the queue
        System.out.println(
            "The elements in the queue are:");
        for (Integer i : queue)
            System.out.print(i + " ");
  
        System.out.println();
  
        // create another queue to demonstrate transfer
        // method
        TransferQueue g
            = new LinkedTransferQueue();
  
        new Thread(new Runnable() {
            public void run()
            {
                try {
                    System.out.println("Transferring"
                                       + " an element");
  
                    // Transfer a String element
                    // using transfer() method
                    g.transfer("is a computer"
                               + " science portal.");
                    System.out.println(
                        "Element "
                        + "transfer is complete");
                }
                catch (InterruptedException e1) {
                    System.out.println(e1);
                }
                catch (NullPointerException e2) {
                    System.out.println(e2);
                }
            }
        })
            .start();
  
        try {
  
            // Get the transferred element
            System.out.println("Geeks for Geeks "
                               + g.take());
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出
adding 15 true
The elements in the queue are:
10 11 12 13 14 15 16 17 18 19 20 
Transferring an element
Element transfer is complete
Geeks for Geeks is a computer science portal.

2. 删除元素

LinkedTransferQueue 提供的remove()方法实现用于删除该队列中存在的元素。

Java

// Java Program Demonstrate removing
// elements of TransferQueue
  
import java.util.concurrent.*;
  
class RemoveElementsExample {
    public static void main(String[] args)
    {
        // Initializing the queue
        TransferQueue queue
            = new LinkedTransferQueue();
  
        // Adding elements to this queue
        for (int i = 1; i <= 5; i++)
            queue.add(i);
  
        // Printing the elements of the queue
        System.out.println(
            "The elements in the queue are:");
        for (Integer i : queue)
            System.out.print(i + " ");
  
        // remove() method will remove the specified
        // element from the queue
        queue.remove(1);
        queue.remove(5);
  
        // Printing the elements of the queue
        System.out.println("\nRemaining elements in queue : ");
        for (Integer i : queue)
            System.out.print(i + " ");
    }
}
输出
The elements in the queue are:
1 2 3 4 5 
Remaining elements in queue : 
2 3 4

3. 迭代

LinkedTransferQueue 提供的iterator()方法实现用于以适当的顺序返回此队列中元素的迭代器。

Java

// Java Program Demonstrate 
// iterating over TransferQueue
  
import java.util.Iterator;
import java.util.concurrent.*;
  
class IteratingExample {
    public static void main(String[] args)
    {
  
        // Initializing the queue
        TransferQueue queue
            = new LinkedTransferQueue();
  
        // Adding elements to this queue
        queue.add("Gfg");
        queue.add("is");
        queue.add("fun!!");
  
        // Returns an iterator over the elements
        Iterator iterator = queue.iterator();
  
        // Printing the elements of the queue
        while (iterator.hasNext())
            System.out.print(iterator.next() + " ");
    }
}
输出
Gfg is fun!! 

TransferQueue 的方法

METHOD

DESCRIPTION

getWaitingConsumerCount()Returns an estimate of the number of consumers waiting to receive elements via BlockingQueue.take() or timed poll.
hasWaitingConsumer()Returns true if there is at least one consumer waiting to receive an element via BlockingQueue.take() or timed poll.
transfer​(E e)Transfers the element to a consumer, waiting if necessary to do so.
tryTransfer​(E e)Transfers the element to a waiting consumer immediately, if possible.
tryTransfer​(E e, long timeout, TimeUnit unit)Transfers the element to a consumer if it is possible to do so before the timeout elapses.

在接口Java.util.concurrent.BlockingQueue 中声明的方法

METHODDESCRIPTION
add​(E e)Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.
contains​(Object o)Returns true if this queue contains the specified element.
drainTo​(Collection c)Removes all available elements from this queue and adds them to the given collection.
drainTo​(Collection c, int maxElements)Removes at most the given number of available elements from this queue and adds them to the given collection.
offer​(E e)Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and false if no space is currently available.
offer​(E e, long timeout, TimeUnit unit)Inserts the specified element into this queue, waiting up to the specified wait time if necessary for space to become available.
poll​(long timeout, TimeUnit unit)Retrieves and removes the head of this queue, waiting up to the specified wait time if necessary for an element to become available.
put​(E e)Inserts the specified element into this queue, waiting if necessary for space to become available.
remainingCapacity()Returns the number of additional elements that this queue can ideally (in the absence of memory or resource constraints) accept without blocking, or Integer.MAX_VALUE if there is no intrinsic limit.
remove​(Object o)Removes a single instance of the specified element from this queue, if it is present.
take()Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.

在接口Java.util.Collection 中声明的方法

METHODDESCRIPTION
addAll​(Collection c)Adds all of the elements in the specified collection to this collection (optional operation).
clear()Removes all of the elements from this collection (optional operation).
containsAll​(Collection c)Returns true if this collection contains all of the elements in the specified collection.
equals​(Object o)Compares the specified object with this collection for equality.
hashCode()Returns the hash code value for this collection.
isEmpty()Returns true if this collection contains no elements.
iterator()Returns an iterator over the elements in this collection.
parallelStream()Returns a possibly parallel Stream with this collection as its source.
removeAll​(Collection c)Removes all of this collection’s elements that are also contained in the specified collection (optional operation).
removeIf​(Predicate filter)Removes all of the elements of this collection that satisfy the given predicate.
retainAll​(Collection c)Retains only the elements in this collection that are contained in the specified collection (optional operation).
size()Returns the number of elements in this collection.
spliterator()Creates a Spliterator over the elements in this collection.
stream()Returns a sequential Stream with this collection as its source.
toArray()Returns an array containing all of the elements in this collection.
toArray​(IntFunction generator)Returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array.
toArray​(T[] a)Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.

在接口Java.lang.Iterable 中声明的方法

METHODDESCRIPTION
forEach​(Consumer action)Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

在接口Java .util.Queue 中声明的方法

METHODDESCRIPTION
element()Retrieves, but does not remove, the head of this queue.
peek()Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
poll()Retrieves and removes the head of this queue, or returns null if this queue is empty.
remove()Retrieves and removes the head of this queue.

参考: Java : Java