共計(jì) 937 個(gè)字符,預(yù)計(jì)需要花費(fèi) 3 分鐘才能閱讀完成。
在 Java 中,可以使用 BlockingQueue
接口來(lái)實(shí)現(xiàn)阻塞隊(duì)列。BlockingQueue
接口繼承自 Queue
接口,它提供了一種線(xiàn)程安全的隊(duì)列實(shí)現(xiàn),支持在隊(duì)列為空時(shí)等待元素被添加,或者在隊(duì)列已滿(mǎn)時(shí)等待空間被釋放。
常用的 BlockingQueue
實(shí)現(xiàn)類(lèi)包括 ArrayBlockingQueue
、LinkedBlockingQueue
、PriorityBlockingQueue
等。
以下是一個(gè)使用 ArrayBlockingQueue
實(shí)現(xiàn)阻塞隊(duì)列的示例:
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class BlockingQueueExample {public static void main(String[] args) {BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
// 生產(chǎn)者線(xiàn)程
Thread producer = new Thread(() -> {try {for (int i = 0; i < 10; i++) {queue.put(i); // 向隊(duì)列中添加元素
System.out.println("Produced: " + i);
}
} catch (InterruptedException e) {e.printStackTrace();
}
});
// 消費(fèi)者線(xiàn)程
Thread consumer = new Thread(() -> {try {for (int i = 0; i < 10; i++) {int value = queue.take(); // 從隊(duì)列中取出元素
System.out.println("Consumed: " + value);
}
} catch (InterruptedException e) {e.printStackTrace();
}
});
producer.start();
consumer.start();}
}
在上面的示例中,生產(chǎn)者線(xiàn)程向 ArrayBlockingQueue
中添加元素,消費(fèi)者線(xiàn)程從隊(duì)列中取出元素。如果隊(duì)列已滿(mǎn)或者為空時(shí),線(xiàn)程會(huì)被阻塞,直到隊(duì)列中有空間或者有元素可取。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完