多线程(4)
  TEZNKK3IfmPf 2023年11月14日 12 0
  1定义:显示声明的锁,比如reentrantlock

非显示锁sychronized

公平锁,非公平锁

  1定义:这个是reentrantlock底层,默认为非公平锁,速度快

读写锁

  1:reentrantlock的分为读写锁,口诀:读读共享,写写互斥,读写互斥
  2:应用场景:多读写少的场景

阻塞与唤醒 Condition

  1:对于同一个lock,可以加上Condition进行等待唤醒控制
  2:比如生产者消费者问题:
package cn.enjoyedu.ch4.rw;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;

public class Test1 {

    private static Lock lock = new ReentrantLock();
    private static Condition notEmpty = lock.newCondition();
    private static Condition notFull = lock.newCondition();
    private static volatile  int count = 0;
    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(6);
        pool.execute(new Gun(lock, notEmpty, notFull));
        pool.execute(new Bullet(lock, notEmpty, notFull));
    }

    public static class Gun implements Runnable {
        private Lock lock;
        private Condition notEmpty;
        private Condition notFull;

        public Gun(Lock lock, Condition notEmpty, Condition notFull) {
            this.lock = lock;
            this.notEmpty = notEmpty;
            this.notFull = notFull;
        }

        public void run() {
            while (true) {
                lock.lock();
                while (count == 0) {
                    try {
                        notEmpty.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("射击---biubiubiu");
                count--;
                notFull.signal();
                lock.unlock();
            }
        }
    }

    public static class Bullet implements Runnable {

        private Lock lock;
        private Condition notEmpty;
        private Condition notFull;

        public Bullet(Lock lock, Condition notEmpty, Condition notFull) {
            this.lock = lock;
            this.notEmpty = notEmpty;
            this.notFull = notFull;
        }

        public void run() {
            while (true) {
                lock.lock();
                while (count >= 20) {
                    try {
                        notFull.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("压入子弹---铛铛");
                count++;
                notEmpty.signal();
                lock.unlock();
            }
        }
    }
}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2023年11月14日   35   0   0 多线程qt
TEZNKK3IfmPf