Java线程同步:生产者-消费者 模型(代码示例)

/ Java / 没有评论 / 2042浏览
public class ThreadSyn {  
      
    public static void main(String[] args) {  
        new ThreadSyn();  
    }  
  
    public ThreadSyn() {  
        Queue queue = new Queue();  
  
        Producter p = new Producter(queue);  
        Consumer c = new Consumer(queue);  
  
        p.start();  
        c.start();  
    }  
  
      
    // Queue模拟Java线程同步中的生产者消费者仓库、队列。  
    private class Queue {  
        int value; // 为了使例子简单,value即为假设长度为1的仓库、队列  
        boolean full = false;  
  
        public synchronized void put(int i) {  
            if (!full) {  
                value = i;  
                full = true;  
  
                notify();  
            }  
  
            try {  
                wait();  
            } catch (InterruptedException e) {  
                // e.printStackTrace();  
            }  
        }  
  
        public synchronized int get() {  
            if (!full)  
                try {  
                    wait();  
                } catch (InterruptedException e) {  
                    // e.printStackTrace();  
                }  
  
            full = false;  
  
            notify();  
  
            return value;  
        }  
    }  
  
      
    // Java线程同步模型-生产者  
    private class Producter extends Thread {  
        private Queue q;  
  
        public Producter(Queue q) {  
            this.q = q;  
        }  
  
        public void run() {  
            for (int i = 0; i < 20; i++) {  
                System.out.println("生产了:" + i);  
                q.put(i);  
            }  
        }  
    }  
  
    // Java线程同步模型-消费者  
    private class Consumer extends Thread {  
        private Queue q;  
  
        public Consumer(Queue q) {  
            this.q = q;  
        }  
  
        public void run() {  
            while (true) {  
                System.out.println("消费了:" + q.get());  
            }  
        }  
    }  
}