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

锁是什么,锁锁的是谁?

相关推荐
云边小网安1 小时前
java集合(十) ---- LinkedList 类
java·开发语言·青少年编程·java集合
乐神嘎嘎嘎1 小时前
springboot速通
java·spring boot
Zephyrtoria2 小时前
区间合并:区间合并问题
java·开发语言·数据结构·算法
yuren_xia6 小时前
RabbitMQ 知识详解(Java版)
java·rabbitmq·java-rabbitmq
kfyty7257 小时前
轻量级 ioc 框架 loveqq,支持接口上传 jar 格式的 starter 启动器并支持热加载其中的 bean
java·jvm·ioc·jar·热加载
早起鸟儿8 小时前
docker-Dockerfile 配置
java·linux·运维·docker
云边小网安8 小时前
java集合篇(六) ---- ListIterator 接口
java·开发语言·青少年编程·java集合
都叫我大帅哥8 小时前
Spring WebFlux:响应式编程的“未来战士”还是“花架子”?
java·spring·flux
都叫我大帅哥8 小时前
Reactor 深度解析:响应式编程的「核反应堆」是如何工作的?
java·spring
不太厉害的程序员8 小时前
NC65配置xml找不到Bean
xml·java·后端·eclipse