1. 程式人生 > >java每日一練------生產者消費者(執行緒)

java每日一練------生產者消費者(執行緒)

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.Random;

public class ProductorCumstomerQueue {
    private static final BlockingQueue<Integer> queue = new LinkedBlockingQueue<Integer>();
    private static Random rand =new Random();
    private static List<Thread> threads = new ArrayList<Thread>();
    public static void main(String []args) {
        for(int i=0; i<2; i++) {
            Thread pro = new Thread(new Productor());
            threads.add(pro);
        }
        for(int i=0; i<1; i++) {
            Thread cus = new Thread(new Customer());
            threads.add(cus);
        }

        for(int i=0; i<threads.size();i++) {
            Thread t = (Thread)threads.get(i);
            t.start();
        }

    }
    
    public static class Productor implements Runnable{
        public void run() {
            while(true) {
                try {
                    //隨機數[0,10)整數
                    int num = rand.nextInt(10);
                    queue.put(num);
                    System.out.println("已生產"+num+"號油條");
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    
    public static class Customer implements Runnable{
        public void run() {
            while(true) {
                try {
                    int num = queue.take();
                    System.out.println("成功消費"+num+"號油條,當前還剩"+queue.size());
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    
}