It
is an optionally bounded blocking queue, based on Linked Node
implementation. You can specify the size of LinkedBlockingQueue at
the time of instantiation, If no size specified, then
LinkedBlockingQueue can grow up to Integer.MAX_VALUE. This class is a
member of the Java Collections Framework.
Constructors
1. public LinkedBlockingQueue()
Creates a LinkedBlockingQueue with a capacity of Integer.MAX_VALUE.
2. public LinkedBlockingQueue(int capacity)
Creates a LinkedBlockingQueue with the given (fixed) capacity.
3. public LinkedBlockingQueue(Collection<? extends E> c)
Creates a LinkedBlockingQueue with a capacity of Integer.MAX_VALUE, initially containing the elements of the given collection. The elements in the collection are added using collection iterator.
Constructors
1. public LinkedBlockingQueue()
Creates a LinkedBlockingQueue with a capacity of Integer.MAX_VALUE.
2. public LinkedBlockingQueue(int capacity)
Creates a LinkedBlockingQueue with the given (fixed) capacity.
3. public LinkedBlockingQueue(Collection<? extends E> c)
Creates a LinkedBlockingQueue with a capacity of Integer.MAX_VALUE, initially containing the elements of the given collection. The elements in the collection are added using collection iterator.
import java.util.concurrent.LinkedBlockingQueue; public class Producer implements Runnable{ LinkedBlockingQueue<Integer> queue; Producer(LinkedBlockingQueue q){ queue = q; } @Override public void run(){ int i=0; while(true){ i++; try { queue.put(i); System.out.println(Thread.currentThread().getName() + " : " + i); Thread.sleep(100); } catch (InterruptedException ex) { } } } }
import java.util.concurrent.LinkedBlockingQueue; public class Consumer implements Runnable{ LinkedBlockingQueue<Integer> queue; Consumer(LinkedBlockingQueue q){ queue = q; } @Override public void run(){ while(true){ try { System.out.println("Consumer : " + queue.take()); Thread.sleep(100); } catch (InterruptedException ex) { } } } }
import java.util.concurrent.LinkedBlockingQueue; public class LinkedBlockingQueueEx { public static void main(String args[]){ LinkedBlockingQueue<Integer> q = new LinkedBlockingQueue(5); Producer p1 = new Producer(q); Producer p2 = new Producer(q); Consumer con = new Consumer(q); Thread t1 = new Thread(p1); t1.setName("Producer1"); Thread t2 = new Thread(p2); t2.setName("Producer2"); Thread t3 = new Thread(con); t3.setName("Con"); t1.start(); t2.start(); t3.start(); } }
Output
Producer2 : 1 Consumer : 1 Producer1 : 1 Consumer : 1 Producer2 : 2 Producer1 : 2 Consumer : 2 Producer1 : 3 Producer2 : 3 Producer1 : 4 Consumer : 2 … … …
No comments:
Post a Comment