Android 实现一个生产者-消费者模式的循环队列

要实现一个生产者-消费者模式的循环队列,当队列满时等待空闲空间,当队列为空时等待数据,可以使用 Java 的 wait 和 notify 方法来实现线程间的同步和通信。

以下是一个线程安全的、支持等待和通知机制的循环队列实现:
CircularQueue 类

public class CircularQueue<T> {
    private T[] queue;
    private int front;
    private int rear;
    private int size;
    private int count;
    
    public CircularQueue(int k) {
        queue = (T[]) new Object[k];
        front = 0;
        rear = 0;
        size = k;
        count = 0;
    }

    public synchronized void enQueue(T value) throws InterruptedException {
        while (isFull()) {
            wait();
        }
        if (isEmpty()) {
            notifyAll();
        }
        queue[rear] = value;
        rear = (rear + 1) % size;
        count++;
    }

    public synchronized T deQueue() throws InterruptedException {
        while (isEmpty()) {
            wait();
        }
        if (isFull()) {
            notifyAll();
        }
        T value = queue[front];
        queue[front] = null;
        front = (front + 1) % size;
        count--;
        return value;
    }

    public synchronized T Front() {
        return isEmpty() ? null : queue[front];
    }

    public synchronized T Rear() {
        return isEmpty() ? null : queue[(rear - 1 + size) % size];
    }

    public synchronized boolean isEmpty() {
        return count == 0;
    }

    public synchronized boolean isFull() {
        return count == size;
    }
}

MainActivity 类

在 Android 应用中测试这个线程安全的循环队列,通过不同的线程模拟生产者和消费者。

import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize a CircularQueue with capacity 5 for String objects
        CircularQueue<String> stringQueue = new CircularQueue<>(5);

        // Producer thread to enqueue elements
        Thread producer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    stringQueue.enQueue("Element " + i);
                    Log.d("Producer", "Enqueued: Element " + i);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        // Consumer thread to dequeue elements
        Thread consumer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    String element = stringQueue.deQueue();
                    Log.d("Consumer", "Dequeued: " + element);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        // Start the threads
        producer.start();
        consumer.start();

        // Wait for the threads to finish
        try {
            producer.join();
            consumer.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        Log.d("MainActivity", "Program ended.");
    }
}

解释:

CircularQueue Class:
    1) 使用泛型 T 来定义循环队列,使其能够存储任何类型的对象。
    2) 添加了 count 变量来跟踪当前队列中的元素数量。
    3) enQueue 方法:在队列满时等待,有空闲空间后插入元素并唤醒所有等待线程。
    4) deQueue 方法:在队列为空时等待,有数据后取出元素并唤醒所有等待线程。
    5) Front 和 Rear 方法:获取队列头部和尾部元素。
    6) isEmpty 方法:检查队列是否为空。
    7) isFull 方法:检查队列是否已满。

MainActivity Class:
    1) 初始化一个容量为 5 的 CircularQueue,用于存储 String 对象。
    2) 创建生产者线程,不断将元素添加到队列中。
    3) 创建消费者线程,不断从队列中取出元素。
    4) 两个线程分别调用 enQueue 和 deQueue 方法,并通过日志输出验证方法的正确性。
    5) 等待两个线程结束,确保所有操作完成。

这样,通过使用 wait 和 notify 方法,我们就可以实现一个线程安全的、支持等待和通知机制的循环队列。这适用于生产者-消费者模型,在多线程环境下有效地管理资源。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
下面是一个使用Python的多线程模块实现生产者-消费者模式的示例程序: ```python import threading import time import queue # 生产者线程类 class ProducerThread(threading.Thread): def __init__(self, queue): threading.Thread.__init__(self) self.queue = queue def run(self): for i in range(10): item = "item-" + str(i) self.queue.put(item) print("Produced:", item) time.sleep(1) # 消费者线程类 class ConsumerThread(threading.Thread): def __init__(self, queue): threading.Thread.__init__(self) self.queue = queue def run(self): while True: item = self.queue.get() print("Consumed:", item) time.sleep(2) self.queue.task_done() # 创建一个队列 queue = queue.Queue() # 创建一个生产者线程和一个消费者线程 producer_thread = ProducerThread(queue) consumer_thread = ConsumerThread(queue) # 启动线程 producer_thread.start() consumer_thread.start() # 等待队列被处理完 queue.join() ``` 在这个示例程序中,我们首先定义了一个生产者线程类和一个消费者线程类,分别用于生产和消费数据。然后,我们创建一个队列对象用于存储生产者生产的数据。接着,我们创建一个生产者线程和一个消费者线程,并启动它们。最后,我们使用`queue.join()`方法等待队列被处理完。 需要注意的是,在消费者线程中,我们使用了`queue.task_done()`方法来通知队列已经处理完一个任务。这个方法应该在每次从队列中获取一个任务并处理完之后调用,以便队列能够正确地跟踪任务的状态。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

最乱纷飞的code

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值