锁应用:生产者-消费者模型

lock

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

public class Test{
    public static void main(String args[]){
        Product product = new Product();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                product.Producer();
            }
        },"Producer").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                product.Consumer();
            }
        },"Consumer").start();
    }
}
class Product{
    private int number=0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    //生产者
    public void Producer(){
        lock.lock();
        try{
            while(number!=0){
               condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+"->"+number);
            condition.signal();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            lock.unlock();
        }
    }
    //消费者
    public void Consumer(){
        lock.lock();
        try{
            while(number==0){
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+"->"+number);
            condition.signal();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            lock.unlock();
        }
    }
}

synchronized

只适用单消费者和单生产者模型

public class TestSynchronized {
    public static void main(String args[]){
        Product product = new Product();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    product.Producer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"Producer").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    product.Consumer();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"Consumer").start();
    }
}
class Product{
    private int number=0;

    //生产者
    public synchronized void  Producer() throws InterruptedException {
        while(number!=0){
            wait();
        }
        number++;
        System.out.println(Thread.currentThread().getName()+"->"+number);
        notify();
    }
    //消费者
    public synchronized void Consumer() throws InterruptedException {
        while(number==0){
            wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName()+"->"+number);
        notify();
    }
}
Last modification:September 6th, 2020 at 06:43 pm