Skip to content

消息队列(第一版) #1

Open
@pangh-space

Description

@pangh-space

package com.ph.juc;

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

class ShareData{
private int number = 0;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();

public void increment() throws Exception{

    lock.lock();
    try{
        // 1. 判断
        while (number != 0){
            // 等待不能生产
            condition.await();
        }
        // 2. 干活
        number++;
        System.out.println(Thread.currentThread().getName() + "\t " + number);
        // 3.通知、唤醒
        condition.signalAll();
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        lock.unlock();
    }



}

public void decrement() throws Exception{

    lock.lock();
    try{
        // 1. 判断
        while (number == 0){
            // 等待不能生产
            condition.await();
        }
        // 2. 干活
        number--;
        System.out.println(Thread.currentThread().getName() + "\t " + number);
        // 3.通知、唤醒
        condition.signalAll();
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        lock.unlock();
    }



}

}

/**

  • @author panghui
  • @Version 1.0
  • @SInCE 2019-09-03
  • 一个初始值为零的变量,两个线程对其进行交替操作,一个加1一个减1,来5轮
    1. 线程-操作-资源类
    1. 判断-干活-通知
    1. 防止虚假唤醒机制

*/
public class ProdConsumer_TraditionDemo {

public static void main(String[] args) throws Exception{

    ShareData shareData = new ShareData();

    new Thread(()->{

        for (int i = 1; i <= 5; i++) {
            try {
                shareData.increment();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    },"AA").start();

    new Thread(()->{

        for (int i = 1; i <= 5; i++) {
            try {
                shareData.decrement();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    },"BB").start();

}

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions