We are trying take data from blocking queue in multi threaded environment.
As we know blocking queue is thread safe and take data from blocking queue in FIFO manner. But not getting expected output.
Please find below program for reference
package com.example.demo;
class PriceTask implements Runnable {
@Override
public void run() {
while (true) {
try {
String data = QueueData.bq.take();
System.out.println(data);
} catch (Exception ex) {
}
}
}
}
public class SimpleTestDemo {
public static void main(String[] args) throws Exception {
QueueData obj1 = new QueueData();
obj1.m1();
Thread t1 = new Thread(new PriceTask(), "T1");
Thread t2 = new Thread(new PriceTask(), "T2");
t1.start();
t2.start();
}
}
package com.example.demo;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class QueueData {
public static final BlockingQueue<String> bq = new LinkedBlockingQueue<String>();
public void m1() throws InterruptedException {
bq.put("Data--01");
bq.put("Data--02");
bq.put("Data--03");
bq.put("Data--04");
bq.put("Data--05");
bq.put("Data--06");
bq.put("Data--07");
bq.put("Data--08");
bq.put("Data--09");
bq.put("Data--10");
}
}
Getting output as below
Data--01
Data--03
Data--04
Data--05
Data--06
Data--07
Data--08
Data--09
Data--10
Data--02
Expected output
Data--01
Data--02
Data--03
Data--04
Data--05
Data--06
Data--07
Data--08
Data--09
Data--10