具体模型如下:
- 有若干个消费者,每个消费者都可以独立的执行消费任务,偶尔会因为某种原因,该消费者会不可用,这个时候不能在给他分配消费任务了。
- 此外还有大量待消费的生产品,每个消费者都可以一个耗时的IO操作。
- 设计一个对象模型来满足这个场景。
说一些思路,这个问题首先可以使用阻塞队列来直接构建,因为本身就可以直接应用其生产者消费者模型来进行。然后就是一些搭建的思路!
这里将生产者创建一个类,然后再类内创建一个线程专门用来生产!
class Patient{
BlockingQueue<Integer> queue;
Thread thread;
public Patient(BlockingQueue<Integer> queue){
this.queue = queue;
thread = new Thread(new Runnable() {
@Override
public void run() {
produce();
}
});
}
public void produce(){
int i=0;
while (true){
try {
queue.put(i++);
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
然后是消费者这块,也创建一个类,同样类内创建一个线程用来消费产品。并且需要增加一个为了实现要求中“偶尔会因为某种原因,该消费者会不可用”的方法。以及恢复其功能的方法。这里我使用加锁的方式来实现。
class Nurse{
ReentrantLock lock = new ReentrantLock();
BlockingQueue<Integer> queue;
Thread thread;
String str;
public Nurse(BlockingQueue<Integer> queue,String str){
this.str = str;
this.queue = queue;
thread = new Thread(new Runnable() {
@Override
public void run() {
while (!queue.isEmpty()){
try {
lock.lock();
Integer integer = queue.take();
System.out.println(str+"正在处理"+integer);
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
});
}
//停止护士的工作
public void stop(){
lock.lock();
System.out.println(this.str+"停止工作");
}
public void reset(){
lock.unlock();
System.out.println(this.str+"重新工作");
}
}
最终则在主函数中,只需要创建生产者和相应的消费者即可。
public class application_BlockingQueue {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(20);
Patient patient = new Patient(queue);
Nurse n1 = new Nurse(queue,"nurse1");
Nurse n2 = new Nurse(queue,"nurse2");
patient.thread.start();
n1.thread.start();
n2.thread.start();
Thread.sleep(300);
n1.stop();
Thread.sleep(1500);
n1.reset();
}
}
最终效果如下: