打印机-顾客进程同步
程序员文章站
2024-03-15 08:26:17
...
系统中有一个打印进程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();
}
}
}
}