高级农民
- 积分
- 2508
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2020-1-21
- 最后登录
- 1970-1-1
|
在网上看了一下,照猫画虎写了一个,不知道对不对
- public class ThreadExample {
- public static class PC {
- private Queue<Integer> dataQueue;
- private int cap;
- public void init(int cap) {
- this.cap = cap;
- dataQueue = new ArrayDeque<>();
- }
- // Function called by producer thread
- public void put (int data) throws InterruptedException {
- while(true) {
- synchronized (this) {
- // producer thread waits while list is full
- while (dataQueue.size() == cap) {
- wait();
- }
- // to insert the jobs in the list
- dataQueue.offer(data);
- System.out.println("Put new data: " + data);
- // notifies the consumer thread that now it can start consuming
- notify();
- // makes the working of program easier to understand
- Thread.sleep(1000);
- }
- }
- }
- public void put (List<Integer> dataList) throws InterruptedException{
- while(true) {
- synchronized (this) {
- // producer thread waits while list is full
- while (dataQueue.size() == cap) {
- wait();
- }
- // to insert the jobs in the list
- int i = 0;
- while (dataQueue.size() < cap && i < dataList.size()) {
- put(dataList.get(i));
- i++;
- }
- // notifies the consumer thread that now it can start consuming
- notify();
- // makes the working of program easier to understand
- Thread.sleep(1000);
- }
- }
- }
- // Function called by consumer thread
- public int get() throws InterruptedException{
- while (true) {
- synchronized (this) {
- // consumer thread waits while list is empty
- while (dataQueue.size() == 0) {
- wait();
- }
- // to retrieve the first job in the list
- int val = dataQueue.poll();
- // Wake up producer thread
- notify();
- // and sleep
- Thread.sleep(1000);
- return val;
- }
- }
- }
- }
- }
复制代码 |
|