JUC并发编程1

什么是juc

在java的java.util.concurrent包下的工具。

传统的synchronize

java 复制代码
public class SealTicket {
    int total = 50;
    public synchronized void seal() {
        if (total > 0) {
            System.out.println(Thread.currentThread().getName()
                    + "卖出第"
                    + (total--)
                    + "张,剩余:" + total
            );
        }
    }
}

JUC 的锁

java 复制代码
public class SealTicket {
    int total = 50;
    Lock lock = new ReentrantLock();
    public void seal() {
         lock.lock();
        if (total > 0) {
            System.out.println(Thread.currentThread().getName()
                    + "卖出第"
                    + (total--)
                    + "张,剩余:" + total
            );
        }
        lock.unlock();
    }
}

Synchronize 和 Lock的区别

生产者和消费者问题

版本 synchronize

java 复制代码
public class Data {

    int i = 0;
    public synchronized void add() throws InterruptedException {
        if (i != 0) {
            this.wait();
        }
        i++;
        System.out.println(Thread.currentThread().getName() + "=="+ i);
        this.notifyAll();
    }
    public synchronized void remove() throws InterruptedException {
        if (i == 0) {
            this.wait();
        }
        i--;
        System.out.println(Thread.currentThread().getName() + "=="+ i);
        this.notifyAll();
    }
}


public class Producer {
    public static void main(String[] args) {
        Data data = new Data();
        new Thread(() -> {
            for (int i = 0; i < 60; i++) {
                try {
                    data.add();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "a").start();

        new Thread(() -> {
            for (int i = 0; i < 60; i++) {
                try {
                    data.remove();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "b").start();


//        new Thread(() -> {
//            for (int i = 0; i < 60; i++) {
//                sealTicket.seal();
//            }
//        }, "c").start();


    }
}

版本 Lock

8锁问题

锁是什么,锁锁的是谁?

相关推荐
独立开阀者_FwtCoder6 分钟前
"页面白屏了?别慌!前端工程师必备的排查技巧和面试攻略"
java·前端·javascript
Touper.10 分钟前
JavaSE -- 泛型详细介绍
java·开发语言·算法
静若繁花_jingjing27 分钟前
Redis线程模型
java·数据库·redis
hello早上好1 小时前
CGLIB代理核心原理
java·spring
魔镜魔镜_谁是世界上最漂亮的小仙女1 小时前
java-web开发
java·后端·架构
爱吃小土豆豆豆豆1 小时前
定时器和守护线程
java
Seven971 小时前
了解GC吗?什么是GC?
java
Edingbrugh.南空1 小时前
Flink ClickHouse 连接器维表源码深度解析
java·clickhouse·flink
掘金-我是哪吒2 小时前
分布式微服务系统架构第157集:JavaPlus技术文档平台日更-Java多线程编程技巧
java·分布式·微服务·云原生·架构
飞翔的佩奇2 小时前
Java项目:基于SSM框架实现的忘忧小区物业管理系统【ssm+B/S架构+源码+数据库+毕业论文+开题报告】
java·数据库·mysql·vue·毕业设计·ssm框架·小区物业管理系统