java中创建一个对列,当队列长度达到2000条,跑一条单线程用来消费对列中的数据
- User
java中创建一个对列,当队列长度达到2000条,跑一条单线程用来消费对列中的数据
- Assistant
你可以使用
java.util.Queue接口的实现类java.util.LinkedList来创建一个队列,并利用一个单线程来消费队列中的数据。以下是一个示例代码:import java.util.LinkedList; import java.util.Queue; public class Main { public static void main(String[] args) { Queue<String> queue = new LinkedList<>(); // 生产者线程:向队列中添加数据 Thread producerThread = new Thread(() -> { int count = 0; while (true) { synchronized (queue) { while (queue.size() >= 2000) { try { queue.wait(); // 队列已满,生产者线程等待 } catch (InterruptedException e) { e.printStackTrace(); } } String data = "Data " + count++; queue.add(data); System.out.println("Produced: " + data); queue.notifyAll(); // 通知消费者线程可以消费数据 } } }); // 消费者线程:从队列中消费数据 Thread consumerThread = new Thread(() -> { while (true) { synchronized (queue) { while (queue.isEmpty()) { try { queue.wait(); // 队列为空,消费者线程等待 } catch (InterruptedException e) { e.printStackTrace(); } } String data = queue.poll(); System.out.println("Consumed: " + data); queue.notifyAll(); // 通知生产者线程可以继续生产数据 } } }); producerThread.start(); consumerThread.start(); } } - User
java中单独跑一个线程,每当对列中数据达到100条开始消费数据,消费完清空对列
- Assistant
以下是使用
java.util.concurrent.LinkedBlockingQueue实现的示例代码,该队列实现了java.util.Queue接口,并且是线程安全的:import java.util.Queue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class Main { public static void main(String[] args) { BlockingQueue<String> queue = new LinkedBlockingQueue<>(); // 生产者线程:向队列中添加数据 Thread producerThread = new Thread(() -> { int count = 0; while (true) { try { String data = "Data " + count++; queue.put(data); System.out.println("Produced: " + data); if (queue.size() >= 100) { break; } } catch (InterruptedException e) { e.printStackTrace(); } } }); producerThread.start(); // 消费者线程:从队列中消费数据 Thread consumerThread = new Thread(() -> { while (true) { try { if (queue.isEmpty()) { Thread.sleep(1000); // 队列为空,消费者线程暂停1秒钟 continue; // 继续检查队列是否为空 } String data = queue.poll(); System.out.println("Consumed: " + data); if (queue.isEmpty()) { break; } } catch (InterruptedException e) { e.printStackTrace(); } } }); consumerThread.start(); } }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.