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锁问题

锁是什么,锁锁的是谁?

相关推荐
武子康32 分钟前
Java-72 深入浅出 RPC Dubbo 上手 生产者模块详解
java·spring boot·分布式·后端·rpc·dubbo·nio
_殊途1 小时前
《Java HashMap底层原理全解析(源码+性能+面试)》
java·数据结构·算法
椰椰椰耶2 小时前
【Spring】拦截器详解
java·后端·spring
没有bug.的程序员3 小时前
JAVA面试宝典 - 《MyBatis 进阶:插件开发与二级缓存》
java·面试·mybatis
没有羊的王K4 小时前
SSM框架学习——day1
java·学习
又菜又爱coding4 小时前
安装Keycloak并启动服务(macOS)
java·keycloak
不知道叫什么呀5 小时前
【C】vector和array的区别
java·c语言·开发语言·aigc
wan_da_ren5 小时前
JVM监控及诊断工具-GUI篇
java·开发语言·jvm·后端
cui_hao_nan6 小时前
JAVA并发——什么是Java的原子性、可见性和有序性
java·开发语言
best_virtuoso6 小时前
JAVA JVM垃圾收集
java·开发语言·jvm