java阻塞队列基础

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
SynchoronousQueue
在这里插入图片描述
在这里插入图片描述
生产者消费者(传统版)
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
synchronized和Lock有什么区别?用新的lock有什么好处?
1.原始构成

synchronized是关键字属于jvm层面,

monitorenter(底层是通过monitor对象来完成,其实wait/notify等方法也依赖于monitor对象只有在同步块或方法中才能调wait/notify等方法)

monitorexit

Lock是具体类(java.util.concurrent.locks.lock)是api层面的锁

2 使用方法

synchronized不需要用户去手动释放锁,当synchronized代码执行完成后系统会自动让线程释放对锁的占用

Renntrantlock则需要用户去手动释放锁若没有主动释放锁,就可能出现死锁现象。

需要lock()和unlock()方法配合try/finally语句块来完成

3.等待是否可中断

synchronized不可中断,除非抛出异常或者正常运行完成

Renntrantlock可中断, 1.设置超时方法trylock(long timeout,TimeUnit unit)

     2.LockInterruptibly()放代码块中,调用interrupt()方法可中断

4.加锁是否公平

synchronized非公平锁

reentrantlock晾着都可以,默认公平锁,构造方法可以传入boolean值,true为公平锁,false为非公平锁

5.绑定多个条件condition

synchronized没有

RenntrantLock用来实现分组唤醒需要唤醒的线程们,可以精确唤醒,而不是像synchronized要么随机唤醒一个线程要么唤醒全部线程。

锁绑定多个条件Condition

package com.ge.healthcare.cn.apm.masterdata.util;
import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;
/** 
* 多线程之间按顺序调用,实现A->B-C三个线程启动,要求如下: 
* AA打印5次,BB打印10次,CC打印15次 
* 来10轮 
*/class ShareResource{
    private int number=1;//A:1 B:2 C:3    
    private Lock lock = new ReentrantLock();    
    private Condition c1 = lock.newCondition();    
    private Condition c2 = lock.newCondition();    
    private Condition c3 = lock.newCondition();

    public void pring5(){
        lock.lock();        
        try {
            //1。判断            
            while (number != 1){
                c1.await();            
            }
            //2。干活            
            for (int i = 1; i <=5 ; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+number);            
            }
            //3。通知            
            number=2;            
            c2.signal();        
        }catch(Exception e){
            e.printStackTrace();        
        }finally {
            lock.unlock();        
        }
    }
    public void pring10(){
        lock.lock();        
        try {
            //1。判断            
            while (number != 2){
                c2.await();            
            }
            //2。干活            
            for (int i = 1; i <=10 ; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+number);            
            }
            //3。通知            
            number=3;            
            c3.signal();        
        }catch(Exception e){
            e.printStackTrace();        
        }finally {
            lock.unlock();        
        }
    }

    public void pring15(){
        lock.lock();        
        try {
            //1。判断            
            while (number != 3){
                c3.await();            
            }
            //2。干活            
            for (int i = 1; i <=15 ; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+number);            
            }
            //3。通知            
            number=1;            
            c1.signal();        
        }catch(Exception e){
            e.printStackTrace();        
        }finally {
            lock.unlock();        
        }
    }


}
public class SyncAndReentrantLockDemo {
    public static void main(String[] args) {
        ShareResource shareResource = new ShareResource();        
        new Thread(()->{
            for (int i = 1; i <=10 ; i++) {
                shareResource.pring5();            
            }
        },"A").start();        
        new Thread(()->{
            for (int i = 1; i <=10 ; i++) {
                shareResource.pring10();            
            }
        },"B").start();        
        new Thread(()->{
            for (int i = 1; i <=10 ; i++) {
                shareResource.pring15();            
            }
        },"C").start();
    }
}

线程通信使用阻塞队列实现

package com.ge.healthcare.cn.apm.masterdata.util;
import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;
class MyResource {
    private volatile boolean FLAG = true;//默认开启进行生产消费    
    private AtomicInteger atomicInteger = new AtomicInteger();
    BlockingQueue<String> blockingQueue = null;
    
    public MyResource(BlockingQueue<String> blockingQueue) {
        this.blockingQueue = blockingQueue;        
        System.out.println(blockingQueue.getClass().getName());    
    }

    public void myProd() throws Exception {
        String data = null;        
        boolean retValue;        
        while (FLAG) {
            data = atomicInteger.incrementAndGet() + "";            
            retValue = blockingQueue.offer(data, 2L, TimeUnit.SECONDS);            
            if (retValue) {
                System.out.println(Thread.currentThread().getName() + "\t 插入队列" + data + "成功");            
            } else {
                System.out.println(Thread.currentThread().getName() + "\t 插入队列" + data + "失败");            
            }
            TimeUnit.SECONDS.sleep(1L);        
        }
        System.out.println(Thread.currentThread().getName() + "\t 生产结束 表示flag=false,生产动作停止");    }

    public void myConsumer() throws Exception {
        String resule = null;        
        while (FLAG) {
            resule = blockingQueue.poll(2L, TimeUnit.SECONDS);            
            if (null == resule || resule.equalsIgnoreCase("")) {
                FLAG = false;                
                System.out.println(Thread.currentThread().getName() + "\t 超过两秒没有取到蛋糕消费退出");                
                return;            
            }
            System.out.println(Thread.currentThread().getName() + "\t 消费队列" + resule + "成功");        }
    }

    public void stop() throws Exception {
        this.FLAG = false;    
    }
}

/** 
* volatile/CAS/AtomicInteger/BlockQueue/线程交互/原子引用 
*/public class ProdConsumer_BlockQueueDemo {
    public static void main(String[] args) {
        MyResource myResource = new MyResource(new ArrayBlockingQueue<>(10));        
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t 生产线程启动");            
            try {
                myResource.myProd();            
            } catch (Exception e) {
                e.printStackTrace();            
            }
        }, "Prod").start(); 
        
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t 消费线程启动");            
            try {
                myResource.myConsumer();            
            } catch (Exception e) {
                e.printStackTrace();            
            }
        }, "Consumer").start();        
        try {
            TimeUnit.SECONDS.sleep(5);        
        } catch (InterruptedException e) {
            e.printStackTrace();        
        }
        System.out.println("时间到,主线程停止");        
        try {
            myResource.stop();        
        } catch (Exception e) {
            e.printStackTrace();        
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值