博客信息

多线程间通信之生产者消费者jdk1.5升级

发布时间:『 2019-05-29 22:51』  博客类别:java基础  阅读(762)

唤醒同一把锁上所有线程,意味着唤醒己方线程,跟对方线程抢夺cpu资源,己方线程就算抢到了锁,也通过不了flag标识,这是浪费时间。

 

 小李飞刀_线程

 

Jdk1.5中提供了多线程升级解决方案;

将同步synchronize替换成现实Lock操作;

Object中的waitnotifynotifyAll,替换成condition对象;

该对象可以通过Lock锁,进行获取;

 

形象来说,condition对象可以用来给同一把锁上的所有线程进行分类;

 

在该示例中,实现了本方只唤醒对方的操作

小李飞刀_线程

 

相关代码

package com.javaxl.thread;

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

/**
 * @author 小李飞刀
 * @site www.javaxl.com
 * @company
 * @create  2019-05-29 21:34
 * <p>
 * 针对于多生产者消费者操作资源的代码(jdk1.5针对于线程这一块做的改进)
 */
public class Demo5 {
    public static void main(String[] args) {
//        一个资源池
        Res r = new Res();
        Thread in = new Thread(new Input(r));
        Thread out = new Thread(new Output(r));
        in.start();
        out.start();

        Thread in2 = new Thread(new Input(r));
        Thread out2 = new Thread(new Output(r));
        in2.start();
        out2.start();
    }
}

class Res {
    private boolean flag = false;
    private int num = 0;
    private Lock lock = new ReentrantLock();
    private Condition in_condition = lock.newCondition();
    private Condition out_condition = lock.newCondition();

    /**
     * 往资源池中添加资源
     */
    //生产者 t1 t2
    public void set() {
        lock.lock();
        try {
            while (this.flag) {
                in_condition.await();
            }
            System.out.println(Thread.currentThread().getName() + "----------生产者---" + (++num));
            this.flag = true;
            out_condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    //消费者 t3 t4
    public void out() {
        lock.lock();
        try {
            while (!this.flag) {
                out_condition.await();
            }
            System.out.println(Thread.currentThread().getName() + "-消费者---" + num);
            this.flag = false;
            in_condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

}

/**
 * 往资源池中生产
 */
class Input implements Runnable {
    private Res r;


    public Input(Res r) {
        this.r = r;
    }

    @Override
    public void run() {
        while (true) {
                r.set();
        }
    }
}

/**
 * 从资源池消费
 */
class Output implements Runnable {
    private Res r;

    public Output(Res r) {
        this.r = r;
    }

    @Override
    public void run() {
        while (true) {
                r.out();
        }
    }
}


最终版结果

小李飞刀_线程




关键字:     Java线程       线程间通信       生产者消费者  

备案号:湘ICP备19000029号

Copyright © 2018-2019 javaxl晓码阁 版权所有