public class MyThread {
static int i;
public static void main(String[] args) {
TickOffice t = new TickOffice();
Thread t1 = new Thread(new Produce(t));
t1.setName("售票点1");
t1.start();
Thread t2 = new Thread(new Consumer(t));
t2.setName("售票点2");
t2.start();
Thread t3 = new Thread(new Consumer(t));
t3.setName("售票点3");
t3.start();
Thread t4 = new Thread(new Consumer(t));
t4.setName("售票点4");
t4.start();
}
}
class TickOffice {
private int ticket = 0;
private ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(15); //存放5张票的阻塞队列
public synchronized void add(){
if(this.queue.size()>=15){
System.out.println("仓库已满");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
ticket += 1;
try {
queue.put(ticket);
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("产生第"+ticket+"张票");
this.notifyAll();
}
}
public synchronized void get(){
if(this.queue.size()<=0){
System.out.println("缺票等待中");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
System.out.println(Thread.currentThread().getName()+"售出第"+queue.poll()+"张票");
this.notifyAll();
}
}
}
class Produce implements Runnable{
private TickOffice off;
public Produce(TickOffice off) {
this.off = off;
}
@Override
public void run() {
System.out.println("开张");
while (true) {
off.add();
}
}
}
class Consumer implements Runnable{
private TickOffice off;
public Consumer(TickOffice off) {
this.off = off;
}
@Override
public void run() {
System.out.println("消费者开始取走产品");
while(true){
off.get();
}
}
}
相关文章
- Semaphore实现的生产者消费者程序
- 进击的Python【第九章】:paramiko模块、线程与进程、各种线程锁、queue队列、生产者消费者模型
- 并发、并行、同步、异步、全局解释锁GIL、同步锁Lock、死锁、递归锁、同步对象/条件、信号量、队列、生产者消费者、多进程模块、进程的调用、Process类、
- python 归纳 (十四)_队列Queue实现生产者消费者
- 高并发:阻塞队列 实现生产者-消费者模式
- phread_con_wait和pthread_mutex_lock实现的生产者消费者模型
- Python之两种模式的生产者消费者模型详解
- Ruby中用线程实现经典的生产者消费者问题代码实例
- Java阻塞队列中的异类,SynchronousQueue底层实现原理剖析
- SpringBoot整合RabbitMQ, 实现生产者与消费者的功能