synchronized的写法

class PCdemo{
public static void main(String[] args) {
//多个线程操作同一资源
Data data = new Data(); new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"thread-1").start(); new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"thread-2").start(); new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"thread-3").start(); new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"thread-4").start();
}
}
//这是一个资源类,
class Data {
private int num = 0;
//加1
public synchronized void increment() throws InterruptedException {
while(num != 0){
this.wait();
}
num++;
System.out.println("当前线程名字:" + Thread.currentThread().getName() + "加1 操作, num为" + num);
this.notifyAll();
}
//减1
public synchronized void decrement() throws InterruptedException {
while(num == 0){
this.wait();
}
num--;
System.out.println("当前线程名字:" + Thread.currentThread().getName() + "减1 操作, num为" + num);
this.notifyAll();
}
}

结果:

这里需要注意一个概念: 虚假唤醒,就是说线程被唤醒了, 但不会被通知 如果把资源类Data中的 increment, decrement方法中的while 换为: if, 那么运行的时候, 二个线程的结果是正常的, 如果二个以上就会出错,结果为

JUC 版本的 生产者和消费者问题

public class JucPCdemo {
public static void main(String[] args) {
//JUC 版本的 就是来替代 synchronized版本的
DataJ data = new DataJ();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"thread-1").start(); new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"thread-2").start(); new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"thread-3").start(); new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"thread-4").start();
} } class DataJ{
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition(); private int num = 0;
//加1
public void increment() throws InterruptedException {
//先加锁
lock.lock();
try {
while(num != 0){
condition.await();//这个替代 this.wait()
}
num++;
System.out.println("当前线程名字:" + Thread.currentThread().getName() + "加1 操作, num为" + num);
condition.signalAll();// 这个来替代 this.notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//释放锁
lock.unlock();
}
}
//减1
public void decrement() throws InterruptedException {
//先加锁
lock.lock();
try {
while(num == 0){
condition.await();//这个替代 this.wait();
}
num--;
System.out.println("当前线程名字:" + Thread.currentThread().getName() + "减1 操作, num为" + num);
condition.signalAll();// 这个来替代 this.notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//释放锁
lock.unlock();
}
}
}

结果同样是正确的

然而 Condition 更强大的是精确通知和精确唤醒, 之前的运行结果线程之间是随机运行的,如果让线程 1,2,3,4 依次循环有序执行, 就要用到Condition

public class JucPCdemo01 {
public static void main(String[] args) {
//JUC 版本的 就是来替代 synchronized版本的
//4个线程依次循环有序执行, num 初始值为0, 线程1--A, 线程2--B, 线程3--C, 线程4--D
DataC data = new DataC();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.printA();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"thread-1").start(); new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.printB();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"thread-2").start(); new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.printC();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"thread-3").start(); new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.printD();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"thread-4").start();
} } class DataC{
private Lock lock = new ReentrantLock();
private Condition condition1 = lock.newCondition();//对应A
private Condition condition2 = lock.newCondition();//对应B
private Condition condition3 = lock.newCondition();//对应C
private Condition condition4 = lock.newCondition();//对应D private String str = "A";
public void printA() throws InterruptedException {
//先加锁
lock.lock();
try {
while(! "A".equals(str)){
condition1.await();//只要不是 A 就等待
}
System.out.println("当前线程名字:" + Thread.currentThread().getName() + "对应str为" + str);
str = "B";
condition2.signal();//这里指定唤醒 线程2 对应B
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//释放锁
lock.unlock();
}
} public void printB() throws InterruptedException {
//先加锁
lock.lock();
try {
while(!"B".equals(str)){
condition2.await();//只要不是B 就等待
}
System.out.println("当前线程名字:" + Thread.currentThread().getName() + "对应str为" + str);
str = "C";
condition3.signal();//这里指定唤醒 线程3 对应C
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//释放锁
lock.unlock();
}
} public void printC() throws InterruptedException {
//先加锁
lock.lock();
try {
while(! "C".equals(str)){
condition3.await();//只要不是C 就等待
}
System.out.println("当前线程名字:" + Thread.currentThread().getName() + "对应str为" + str);
str = "D";
condition4.signal();//这里指定唤醒 线程4 对应D
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//释放锁
lock.unlock();
}
} public void printD() throws InterruptedException {
//先加锁
lock.lock();
try {
while(! "D".equals(str)){
condition4.await();//只要不是D 就等待
}
System.out.println("当前线程名字:" + Thread.currentThread().getName() + "对应str为" + str);
str = "A";
condition1.signal();//这里指定唤醒 线程1 对应A
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//释放锁
lock.unlock();
}
} }

运行结果为;

JUC 并发编程--02,生产者和消费者 synchronized的写法 , juc的写法. Condition的用法的更多相关文章

  1. Java并发编程(4)--生产者与消费者模式介绍

    一.前言 这种模式在生活是最常见的,那么它的场景是什么样的呢? 下面是我假象的,假设有一个仓库,仓库有一个生产者和一个消费者,消费者过来消费的时候会检测仓库中是否有库存,如果没有了则等待生产,如果有就 ...

  2. JUC 并发编程--01,线程,进程,经典卖票案例, juc的写法

    进程: 就是一个程序, 里面包含多个线程, 比如一个QQ程序 线程: 进程中最小的调度单元, 比如 QQ中的自动保存功能 并发: 多个线程操作同一资源, 抢夺一个cpu的执行片段, 快速交替 并行: ...

  3. 并发编程 02—— ConcurrentHashMap

    Java并发编程实践 目录 并发编程 01—— ThreadLocal 并发编程 02—— ConcurrentHashMap 并发编程 03—— 阻塞队列和生产者-消费者模式 并发编程 04—— 闭 ...

  4. JUC并发编程学习笔记

    JUC并发编程学习笔记 狂神JUC并发编程 总的来说还可以,学到一些新知识,但很多是学过的了,深入的部分不多. 线程与进程 进程:一个程序,程序的集合,比如一个音乐播发器,QQ程序等.一个进程往往包含 ...

  5. JUC并发编程与高性能内存队列disruptor实战-上

    JUC并发实战 Synchonized与Lock 区别 Synchronized是Java的关键字,由JVM层面实现的,Lock是一个接口,有实现类,由JDK实现. Synchronized无法获取锁 ...

  6. 并发编程的锁机制:synchronized和lock

    1. 锁的种类 锁的种类有很多,包括:自旋锁.自旋锁的其他种类.阻塞锁.可重入锁.读写锁.互斥锁.悲观锁.乐观锁.公平锁.可重入锁等等,其余就不列出了.我们重点看如下几种:可重入锁.读写锁.可中断锁. ...

  7. JUC并发编程基石AQS之主流程源码解析

    前言 由于AQS的源码太过凝练,而且有很多分支比如取消排队.等待条件等,如果把所有的分支在一篇文章的写完可能会看懵,所以这篇文章主要是从正常流程先走一遍,重点不在取消排队等分支,之后会专门写一篇取消排 ...

  8. python并发编程02 /多进程、进程的创建、进程PID、join方法、进程对象属性、守护进程

    python并发编程02 /多进程.进程的创建.进程PID.join方法.进程对象属性.守护进程 目录 python并发编程02 /多进程.进程的创建.进程PID.join方法.进程对象属性.守护进程 ...

  9. python 并发编程 多进程 生产者消费者模型介绍

    一 生产者消费者模型介绍 为什么要使用生产者消费者模型 生产者指的是生产数据的任务,消费者指的是处理数据的任务, 生产数据目的,是为了给消费者处理. 在并发编程中,如果生产者处理速度很快,而消费者处理 ...

随机推荐

  1. hdu2155 小黑的镇魂曲(dp)

    题意:                             小黑的镇魂曲 Problem Description 这个事情发生在某一天,当小黑和SSJ正在约会的时候,邪恶的Guner抓走了SSJ, ...

  2. hdu5249KPI动态中位数(两个set)

    题意(中问题直接粘题意吧)                                                                      KPI Problem Descr ...

  3. WSL2+Ubuntu配置Java Maven Hadoop Spark环境

    所需文件: 更新日期为2021/5/8: Linux 内核更新包 JDK1.8 maven3.8.1 hadoop3.3.0 spark3.1.1 WSL?WSL2? WSL是适用于 Linux 的 ...

  4. 【vue-02】基础语法

    插值操作 插值运算符 语法:{{数据}} 插值运算符可以对数据进行显示{{msg}},也可以在插值运算符中进行表达式计算{{cnt*2}}. v-html 希望以html格式进行输出 htmlData ...

  5. Mac下配置Git 的全局忽略文件

    $ git config --global core.excludesfile ~/.gitignore_global $ vim ~/.gitignore_global #配置文件参考如下 # fo ...

  6. ppt技巧一四步法调整段落排版

    声明:本文所有截图来源于网易云课堂--<和秋叶一起学PPT>,仅作为个人复习之用,特此声明!

  7. 死磕Spring之AOP篇 - Spring 事务详解

    该系列文章是本人在学习 Spring 的过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring 源码分析 GitHub 地址 进行阅读. Spring 版本:5.1 ...

  8. Redis6.x学习笔记(二)持久化之RDB

    前言 最近学习Redis6.x,特做笔记以备忘,与大家共学.课程是从私塾在线下载的,他们把架构师课程都放出来了,大家可以去下载学习,不要钱的,地址是http://t.hk.uy/eK7,课程很不错,值 ...

  9. 深入源码理解SpringBean生命周期

    概述 本文描述下Spring的实例化.初始化.销毁,整个SpringBean生命周期,聊一聊BeanPostProcessor的回调时机.Aware方法的回调时机.初始化方法的回调及其顺序.销毁方法的 ...

  10. [并发编程 - socketserver模块实现并发、[进程查看父子进程pid、僵尸进程、孤儿进程、守护进程、互斥锁、队列、生产者消费者模型]

    [并发编程 - socketserver模块实现并发.[进程查看父子进程pid.僵尸进程.孤儿进程.守护进程.互斥锁.队列.生产者消费者模型] socketserver模块实现并发 基于tcp的套接字 ...