多线程--生产消费

import java.util.ArrayList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Main {
    public static void main(String[] args) {
        Resource r = new Resource();
        Buy buy = new Buy(r);
        Sale sale = new Sale(r);
        Thread t1 = new Thread(buy);
        Thread t11 = new Thread(buy);
        Thread t2 = new Thread(sale);
        t1.start();
        t11.start();
        t2.start();
    }
}
class Buy implements  Runnable{
    Resource r;

    public Buy(Resource r) {
        this.r = r;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            r.buy();
        }
    }
}
class Sale implements Runnable{
    Resource r;

    public Sale(Resource r) {
        this.r = r;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            r.sale();
        }
    }
}


class Resource {
    private ArrayList<String> list = new ArrayList<>();
    Lock lock = new ReentrantLock();
    Condition buyCondition = lock.newCondition();
    Condition saleCondition = lock.newCondition();
    int i = 0;
    public void buy() {
        lock.lock();
        try {
            while (list.size() == 10) {
                try {
                    buyCondition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.add("name " + i++);
            System.out.println("buy " + "size:" + list.size());
            saleCondition.signal();
        }finally {
            lock.unlock();
        }
    }

    public void sale() {
        lock.lock();
        try {
            while (list.size() == 0) {
                try {
                    saleCondition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.remove(0);
            System.out.println("sale " + "size:" + list.size());
            buyCondition.signal();
        }finally {
            lock.unlock();
        }
    }
}

  

猜你喜欢

转载自www.cnblogs.com/linson0116/p/10395666.html