📚 开源资源分享——颜佐光的个人书架
✉️ 联系站长
书架 / Java / 多线程

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

2017-12-01 17:50 · 约 1,923 字 · 浏览 2,731 次 · 更新 2020-05-07 09:58多线程
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());  
            }  
        }  
    }  
}  
← 返回《Java》目录书架 →