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

锁是什么,锁锁的是谁?

相关推荐
陈天伟教授14 分钟前
Web前端开发 - 制作简单的焦点图效果
java·开发语言·前端·前端开发·visual studio
不吃肘击23 分钟前
MyBatisPlus使用教程
java·开发语言
一刀到底21123 分钟前
spring+tomcat 用户每次发请求,tomcat 站在线程的角度是如何处理用户请求的,spinrg的bean 是共享的吗
java·spring·tomcat
Master-Tang28 分钟前
Spring Boot + MyBatis-Plus实现操作日志记录
java
Ricoh.30 分钟前
打破双亲委派模型的实践:JDBC与Tomcat的深度解析
java·tomcat
我嘞个ddddd30 分钟前
手写Tomcat(一)
java·服务器·tomcat
重整旗鼓~1 小时前
2.微服务-配置
java·spring·微服务
zeijiershuai1 小时前
Mybatis-入门程序、 数据库连接池、XML映射配置文件、MybatisX
xml·java·开发语言·mybatis
java12241 小时前
== 和 equals 的区别
java