我正在使用一个队列,即BlockingQueue。我正在尝试制作一个具有相同优先级的两个线程的应用程序。第一个线程将不断向队列中添加元素,第二个线程将从同一个队列中连续轮询。
程序:
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class Demo {
private final BlockingQueue<Integer> list = new ArrayBlockingQueue<Integer>(10000);
public int count;
public void insert() {
while (true) {
list.add(count);
System.out.println(" inserted : "+count);
count++;
}
}
public void remove() {
while (true) {
try {
int pollElement = (int) list.take();
System.out.println("removed : " + pollElement);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Demo main = new Demo();
Thread thread1 = new Thread() {
@Override
public void run() {
main.insert();
}
};
thread1.start();
Thread thread2 = new Thread() {
@Override
public void run() {
main.remove();
}
};
thread2.start();
}
}
以上程序将经常生成如下输出:
removed : 4992
removed : 4993
inserted : 5195
removed : 4994
inserted : 5196
removed : 4995
inserted : 5197
removed : 4996
inserted : 5198
inserted : 5199
inserted : 5200
inserted : 5201
inserted : 5202
实际要求:
我想要这个应用程序的行为,就好像一个元素被插入队列然后第二个线程得到通知特定的插入操作,以便它可以从同一队列轮询。即我不想要连续插入操作或连续轮询操作。
让我们考虑一下,count变量只不过是连续从服务器中提取数据而不断插入队列。如果在队列上发生连续轮询操作,那么我将丢失在轮询操作正在工作时在该特定时间发生的服务器数据。
答案 0 :(得分:0)
如果我理解正确,您可以使用AtomicBoolean
来模拟它。
private AtomicBoolean aBoolean = new AtomicBoolean(true); // init value - true
然后在insert
和remove
方法
public void insert() {
while (true) {
if(aBoolean.get()) {
list.add(count);
System.out.println(" inserted : "+ count);
count++;
aBoolean.getAndSet(false);
}
}
}
public void remove() {
while (true) {
if(!aBoolean.get()) {
try {
int pollElement = (int) list.take();
System.out.println("removed : " + pollElement);
aBoolean.getAndSet(true);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
因此,如果aBoolean
为true,则只允许插入元素,并删除元素aBoolean
为false。 AtomicBoolean
是thread-safe. After insert/delete you change the
aBoolean``到相反的值,以便其他线程可以执行它的任务。
这是输出:
inserted : 0
removed : 0
inserted : 1
removed : 1
inserted : 2
removed : 2
inserted : 3
removed : 3
inserted : 4
removed : 4
inserted : 5
removed : 5
inserted : 6
removed : 6
inserted : 7
removed : 7