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

锁是什么,锁锁的是谁?

相关推荐
考虑考虑41 分钟前
JDK9中的dropWhile
java·后端·java ee
想躺平的咸鱼干1 小时前
Volatile解决指令重排和单例模式
java·开发语言·单例模式·线程·并发编程
hqxstudying1 小时前
java依赖注入方法
java·spring·log4j·ioc·依赖
·云扬·1 小时前
【Java源码阅读系列37】深度解读Java BufferedReader 源码
java·开发语言
Bug退退退1232 小时前
RabbitMQ 高级特性之重试机制
java·分布式·spring·rabbitmq
小皮侠2 小时前
nginx的使用
java·运维·服务器·前端·git·nginx·github
Zz_waiting.3 小时前
Javaweb - 10.4 ServletConfig 和 ServletContext
java·开发语言·前端·servlet·servletconfig·servletcontext·域对象
全栈凯哥3 小时前
02.SpringBoot常用Utils工具类详解
java·spring boot·后端
兮动人3 小时前
获取终端外网IP地址
java·网络·网络协议·tcp/ip·获取终端外网ip地址
呆呆的小鳄鱼3 小时前
cin,cin.get()等异同点[面试题系列]
java·算法·面试