打印机-顾客进程同步
来源:互联网 发布:sftp用的什么端口 编辑:程序博客网 时间:2024/05/16 19:13
系统中有一个打印进程Printer和若干顾客进程Customer_i(i>20)。缓冲池有5个缓冲区。如果
Customer_i进程要打印,则Printer进程阻塞。当Customer_i进程需要打印时,唤醒Printer进程;如果
没有缓冲区,Customer_i则必须放弃打印。请设计同步机制实现以上要求。
package customer;public class ProducerConsumer {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stub SyncStack ss=new SyncStack(); Printer p=new Printer(ss); Consumer c=new Consumer(ss); new Thread(p).start(); new Thread(c).start();}}class file{int id; file(int id){this.id=id;}public String toString(){return "第:"+id;}}////这个方法是同步的方法,每次只有5个线程可以进来class SyncStack { int index = 0; file[] arrWT = new file[5]; public synchronized void push(file wt) { while(index == arrWT.length) { try { System.out.println("没有空闲的打印机了,请等待!"); System.out.println(wt+"为放弃打印的文件"); this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notifyAll(); arrWT[index] = wt; index ++; System.out.println(wt+"个顾客"+"打印了, "+wt+"份文件"); } public synchronized file pop() { while(index == 0) { try {System.out.println("店里没人了!"); this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notifyAll(); index--; System.out.println(arrWT[index]+"份文件打印完毕,店里剩余"+index+"顾客"); return arrWT[index]; } } class Printer implements Runnable { SyncStack ss = null; Printer(SyncStack ss) { this.ss = ss; } //打印进程 public void run() { for(int i=0; i<25; i++) { file wt = new file(i); ss.push(wt); try{ Thread.sleep((int)(Math.random()*200)); }catch(InterruptedException e){ e.printStackTrace(); } } }}class Consumer implements Runnable { SyncStack ss = null; Consumer(SyncStack ss) { this.ss = ss; } //顾客进程 public void run() { for(int i=0; i<25; i++) { ss.pop(); //System.out.println("打印了: " + wt); try { Thread.sleep((int)(Math.random() * 1000)); } catch (InterruptedException e) { e.printStackTrace(); } } } }
阅读全文
0 0
- 打印机-顾客进程同步
- 销售与顾客的PV同步算法
- Delphi下POS打印机,控制开钱箱,客显,顾客显示屏,小票打印机
- 一个同步打印机的实现
- 进程同步
- 进程同步
- 进程同步
- 进程同步
- 进程同步
- 进程同步
- 进程同步
- 进程同步
- 进程同步
- 进程同步
- 进程同步
- 进程同步
- 进程同步
- 进程同步
- 线段树--点修改(uva12299)
- For , while , do…while的死循环.
- 在php中设置sessionid的httponly属性
- 跟着姜少学Java基础编程之五:Scanner、Random、String
- leetcode 5. Longest Palindromic Substring
- 打印机-顾客进程同步
- IO--打印流
- jQuery基础 | 选择器
- 宏基因组分析教程-Analysis of Metagenomic Data
- java IO笔记(RandomAccessFile)
- 计蒜客 17118 Maximum Flow(2017 ACM-ICPC 亚洲区(西安赛区)网络赛 E)
- SQL Server学习笔记3:数据库中表的插入、删除、修改、合并
- android build system
- 《把时间当作朋友》读书笔记