修改程式語言(高點)  15-38

檔案名稱:P_C.java

import java.io.*;
import java.lang.Math.*;

class Queue
{
    private int que[];
    private int nextIn,nextOut,filled,queSize;
    
    public Queue(int size)
    {
        que=new int[size];
        filled=0;
        nextIn=0;
        nextOut=0;
        queSize=size;
    }

    public synchronized void deposit(int item)
    {        

        try{
            while(filled==queSize)
                wait();
            que[nextIn]=item;
            nextIn=(nextIn+1)%queSize;
            filled++;
            notify();
        }catch(InterruptedException e){}
    }
    
    public synchronized int fetch()
    {
        int item=0;        

        try{
            while(filled==0)
                wait();
            item=que[nextOut];
            nextOut=(nextOut+1)%queSize;
            filled--;
            notify();
        }catch(InterruptedException e){}
        return item;
    }
}

class Producer extends Thread
{
    private Queue buffer;
    public Producer(Queue que)
    {
        buffer=que;
    }

    public void run()
    {
        int new_item;
        for(int i=1;i<=10;i++)
        {
            new_item=(int)(Math.random()*100)+1;
            buffer.deposit(new_item);
            System.out.println(new_item+" is deposited.");
            PAUSE(Math.random());
        }    
    }

    private void PAUSE(double sec)
    {
        try{
            Thread.sleep(Math.round(1000*sec));
        }catch(InterruptedException e){}
    }
}

class Consumer implements Runnable
{
    private Queue buffer;
    public Consumer(Queue que)
    {
        buffer=que;
    }

    public void run()
    {
        int stored_item;
        for(int i=1;i<=10;i++)
        {
            stored_item=buffer.fetch();
            System.out.println(stored_item+" is fetched.");
            PAUSE(Math.random());
        }
    }

    private void PAUSE(double sec)
    {
        try{
            Thread.sleep(Math.round(1000*sec));
        }catch(InterruptedException e){}
    }
}

public class P_C
{
    public static void main(String argv[])
    {
        Queue buff1=new Queue(100);
        Producer producer1=new Producer(buff1);
        Thread consumer1=new Thread(new Consumer(buff1));

        producer1.start();
        consumer1.start();
    }
}

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Rinoa 的頭像
    Rinoa

    褪色的世界.斑剝的記憶

    Rinoa 發表在 痞客邦 留言(0) 人氣()