生产者消费者从低级到高级

 一、使用Lock来模拟生产消费

关键方法:lock()、await()、signalAll()、unlock()

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

/*
 题目:一个初始值为0的变量,两个线程对其交替操作,一个加一一个减一,来5轮
 */
public class ProdConsumer_LockDemo {

    public static void main(String[] args) {
        ShareData shareData = new ShareData();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                shareData.increment();
            }
        },"生产线程").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                shareData.decrement();
            }
        }, "消费线程").start();

    }
}


class ShareData{
    private int number=0;

    private Lock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();

    public void increment(){
        lock.lock();
        try{
            //使用while防止虚假唤醒
            while (number != 0) {
                //等待,不能生产
                condition.await();
            }
            number ++;
            System.out.println(Thread.currentThread().getName()+"\t"+number);
            condition.signalAll();
        }catch (Exception e) {

        }finally {
            lock.unlock();
        }
    }

    public void decrement(){
        lock.lock();
        try{
            //使用while防止虚假唤醒
            while (number == 0) {
                //等待,不能生产
                condition.await();
            }
            number --;
            System.out.println(Thread.currentThread().getName()+"\t"+number);
            condition.signalAll();
        }catch (Exception e) {

        }finally {
            lock.unlock();
        }
    }


}

 

你可能感兴趣的:(Java工具,多线程,lock问题,lock实现生产消费问题)