在Java中,可以使用java.util.concurrent包中的类来实现具有阻塞功能的队列。以下是一些常用的阻塞队列实现:
import java.util.concurrent.ArrayBlockingQueue;
public class BlockingQueueExample {
public static void main(String[] args) throws InterruptedException {
ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
// 生产者线程
Thread producer = new Thread(() -> {
for (int i = 0; i < 20; i++) {
try {
queue.put(i);
System.out.println("Produced: " + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// 消费者线程
Thread consumer = new Thread(() -> {
while (true) {
try {
int item = queue.take();
System.out.println("Consumed: " + item);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
producer.start();
consumer.start();
}
}
Integer.MAX_VALUE。import java.util.concurrent.LinkedBlockingQueue;
public class BlockingQueueExample {
public static void main(String[] args) throws InterruptedException {
LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<>(10);
// 生产者线程
Thread producer = new Thread(() -> {
for (int i = 0; i < 20; i++) {
try {
queue.put(i);
System.out.println("Produced: " + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// 消费者线程
Thread consumer = new Thread(() -> {
while (true) {
try {
int item = queue.take();
System.out.println("Consumed: " + item);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
producer.start();
consumer.start();
}
}
Comparator进行排序。import java.util.concurrent.PriorityBlockingQueue;
public class BlockingQueueExample {
public static void main(String[] args) throws InterruptedException {
PriorityBlockingQueue<Integer> queue = new PriorityBlockingQueue<>();
// 生产者线程
Thread producer = new Thread(() -> {
for (int i = 0; i < 20; i++) {
queue.put(i);
System.out.println("Produced: " + i);
}
});
// 消费者线程
Thread consumer = new Thread(() -> {
while (true) {
try {
int item = queue.take();
System.out.println("Consumed: " + item);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
producer.start();
consumer.start();
}
}
这些阻塞队列类提供了put()和take()方法,分别用于向队列中添加元素和从队列中移除元素。当队列满时,put()方法会阻塞生产者线程;当队列为空时,take()方法会阻塞消费者线程。这样可以实现生产者和消费者之间的同步。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。