C/C++教程

14.线程通信阻塞队列版(lock, await, signal)

本文主要是介绍14.线程通信阻塞队列版(lock, await, signal),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.代码

package com.mydemo;

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

public class TraditionalProducerConsumerDemo {
    public static void main(String[] args) {
        ShareData shareData = new ShareData();
        for (int i1 = 0; i1 < 5; i1++) {
            new Thread(()->{
                try {
                    shareData.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"t1").start();

        }
        for (int i1 = 0; i1 < 5; i1++) {
            new Thread(()->{
                try {
                    shareData.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"t2").start();

        }

    }
}

class ShareData{
    private int number=0;
    private Lock lock=new ReentrantLock();
    private Condition condition=lock.newCondition();
    public void increment() throws InterruptedException {
        lock.lock();
        while (number!=0)
        {
            condition.await();
        }
        number++;
        System.out.println(Thread.currentThread().getName()+"\t "+number);
        condition.signalAll();
        lock.unlock();

    }

    public void decrement() throws InterruptedException {
        lock.lock();
        while (number==0)
        {
            condition.await();
        }
        number-- ;
        System.out.println(Thread.currentThread().getName()+"\t "+number);
        condition.signalAll();
        lock.unlock();




    }






}

2.执行结果

t1     1
t2     0
t1     1
t2     0
t1     1
t2     0
t1     1
t2     0
t1     1
t2     0

 

这篇关于14.线程通信阻塞队列版(lock, await, signal)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!