zoukankan      html  css  js  c++  java
  • The Producer-Consumer Relationship

    //Listing 3-1. The Producer-Consumer Relationship Version 1
    public class PC
    {
        public static void main(String[] args)
        {
            Shared s = new Shared();
            new Producer(s).start();
            new Consumer(s).start();
        }
    }
    
    class Shared
    {
        private char c;
        private volatile boolean writeable = true;
        synchronized void setSharedChar(char c)
        {
            while (!writeable)
            try
            {
             wait();
            }
            catch (InterruptedException ie)
            {
            }
            this.c = c;
            writeable = false;
            notify();
        }
        synchronized char getSharedChar()
        {
            while (writeable)
            try
            {
             wait();
            }
            catch (InterruptedException ie)
            {
            }
            writeable = true;
            notify();
            return c;
        }
    }
    
    class Producer extends Thread
    {
        private final Shared s;
        Producer(Shared s)
        {
         this.s = s;
        }
        @Override
        public void run()
        {
            for (char ch = 'A'; ch <= 'Z'; ch++)
            {
                s.setSharedChar(ch);
                System.out.println(ch + " produced by producer.");
            }
        }
    }
    class Consumer extends Thread
    {
        private final Shared s;
        Consumer(Shared s)
        {
         this.s = s;
        }
        @Override
        public void run()
        {
            char ch;
            do
            {
                ch = s.getSharedChar();
                System.out.println(ch + " consumed by consumer.");
            }
            while (ch != 'Z');
        }
    }
  • 相关阅读:
    Linux
    Python
    Linux
    Python
    爬虫
    WEB
    法正(13):密谋
    法正(12):张松
    法正(11):入川
    法正(10):袍哥
  • 原文地址:https://www.cnblogs.com/rojas/p/5363374.html
Copyright © 2011-2022 走看看