Example of ConcurrentLinkedQueue in Java

By Arvind Rai, November 15, 2023
1. Java ConcurrentLinkedQueue is based on linked node. It is named as ConcurrentLinkedQueue because it is thread safe and can be accessed concurrently. It is available from Java 5.
2. As a property of queue, ConcurrentLinkedQueue follows FIFO. Element is added to the tail of the queue and element is pull out from head.
3. ConcurrentLinkedQueue is used in multi-threaded environment.

Example

package com.concretepage;

import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;


public class ConcurrentLinkedQueueTest {
	
	ConcurrentLinkedQueue<String> clq= new ConcurrentLinkedQueue<String>();
	
	class AddThread implements Runnable{

		@Override
		public void run() {
			//ads the element to the tail of element
			clq.add("A");
			
			//insert the elements to the tail of element
			clq.offer("B");	
			
			// retrieve and removes the elements from head
			clq.poll();
			
			Iterator<String> itr= clq.iterator();
			while(itr.hasNext()){
				System.out.println(itr.next());
			}
	   }
	}
	
   public static void main(String... args){
	   new Thread(new ConcurrentLinkedQueueTest().new AddThread()).start();
	   new Thread(new ConcurrentLinkedQueueTest().new AddThread()).start();
   }
}
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us