JUC并发编程

JUC并发编程

1. 什么是JUC

	源码+官方文档 
	java.util.concurrent 
	java.util.concurrent.atomic 
	java.util.concurrent.locks 

业务:普通的线程代码 Thread
Runnable没有返回值,效率相比Callable相对较低

2.线程和进程

线程,进程,如果不能用一句话说出来的技术,不扎实!

进程:一个程序。QQ.exe  Music.exe 程序的集合
一个进程往往可以包含对个线程,至少包含一个。

Java默认有几个线程?2个 main 和GC

线程:开了一个进程QQ,发送消息(线程负责)
对于Java而言:Thread Runnable  Callable

Java真的可以开启线程吗? 不能的

public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();

        /* Notify the group that this thread is about to be started
         * so that it can be added to the group's list of threads
         * and the group's unstarted count can be decremented. */
        group.add(this);

        boolean started = false;
        try {
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }
//native 修饰是C++写的本地方法,java不能调硬件方面的,因为是运行在虚拟机上的。    
private native void start0();

native 修饰是C++写的本地方法,java不能调硬件方面的,因为是运行在虚拟机上的。

并发与并行的区别

  • 1、并发(Concurrent):指两个或多个事件在同一时间间隔内发生,即交替做不同事的能力,多线程是并发的一种形式。例如垃圾回收时,用户线程与垃圾收集线程同时执行(但不一定是并行的,可能会交替执行),用户程序在继续运行,而垃圾收集程序运行于另一个CPU上。

  • 2、并行(Parallel):指两个或者多个事件在同一时刻发生,即同时做不同事的能力。例如垃圾回收时,多条垃圾收集线程并行工作,但此时用户线程仍然处于等待状态。

package com.zbk.demo01;

public class Test1 {
    public static void main(String[] args) {
        //获取CPU的核数
        //CPU 密集型, IO 密集型
        System.out.println(Runtime.getRuntime().availableProcessors());
    }
}

并发编程的本质:充分利用CPU的资源

线程有几个状态

public enum State {
       //新生
        NEW,

       //运行
        RUNNABLE,

       //阻塞
        BLOCKED,

        //等待  死死的等
        WAITING,

        //超时等待
        TIMED_WAITING,

       //终止
        TERMINATED;
    }

wait与sleep区别

  1. 来自不同的类
    wait => Object
    sleep => Thread
  2. 关于锁的释放
    wait会释放锁
    sleep不会释放锁
  3. 使用的范围是不同的
    wait 必须在同步代码快中
    sleep 可以在任何地方睡

3. Lock锁(重点)

synchronized

package com.zbk.demo01;

//基本的卖票例子

/**
 * 真正的多线程开发,公司中的开发
 * 线程就是一个单独的资源类,没有任何的附属操作
 * 1.属性,方法
 */
public class SaleTicketDemo01 {
    public static void main(String[] args) {
        //并发:  多线程操作同一个资源类
        Ticket ticket = new Ticket();
        new Thread(() -> {
            for (int i = 1; i <= 30; i++) {
                ticket.sale();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 1; i <= 30; i++) {
                ticket.sale();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 1; i <= 30; i++) {
                ticket.sale();
            }
        }, "C").start();

    }
}

//资源类 OOP
class Ticket {
    //属性 方法
    private int number = 20;

    //卖票的方式
    //synchronized   本质:队列 锁
    public synchronized void sale() {
        if (number > 0) {
            number--;
            System.out.println("剩余:" + number);
        }
    }
}

Lock 接口

所有已知实现类: 
ReentrantLock, 可重入锁(常用)
ReentrantReadWriteLock.ReadLock    读锁
ReentrantReadWriteLock.WriteLock    写锁
package com.zbk.demo01;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SaleTicketDemo02 {
    public static void main(String[] args) {
        Ticket2 ticket = new Ticket2();
        new Thread(() -> { for (int i = 1; i <= 30; i++) ticket.sale(); }, "A").start();
        new Thread(() -> { for (int i = 1; i <= 30; i++) ticket.sale(); }, "B").start();
        new Thread(() -> { for (int i = 1; i <= 30; i++) ticket.sale(); }, "C").start();
    }
}

//lock三步曲
//1.new ReentrantLock();
//2.lock();//加锁
//3.finally  => unlock();//解锁
class Ticket2 {
    //属性 方法
    private int number = 20;

    Lock lock = new ReentrantLock();

    public  void sale() {
        lock.lock();//加锁
        try {
            if (number > 0) {
                number--;
                System.out.println("剩余:" + number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//解锁
        }
    }
}

在这里插入图片描述
公平锁:十分公平 可以先来后到
非公平锁:十分不公平, 可以插队(默认)

synchronized与Lock区别

  1. synchronized 内置的Java关键字, Lock是一个Java类
  2. synchronized 无法判断获取锁的状态,Lock可以判断是否获取了锁
  3. synchronized 会自动释放锁,Lock锁必须手动释放锁!如果不释放锁,可能发生死锁
  4. synchronized 线程1:(获得锁 ,阻塞)线程2:(等待,傻傻的等);Lock锁就不一定会等待下去(tryLock);
  5. synchronized 可重入锁,不可以中断,非公平;Lock 可重入锁,可以判断锁,非公平(可以自己设置)
  6. synchronized 适合锁少量的代码同步问题,Lock适合锁大量的同步代码

锁是什么,如何判断锁的是谁!

4.生产者和消费者问题

生产者和消费者问题 synchronized版

package com.zbk.pc;

/**
 * 线程之间的通信问题 : 生产者和消费者问题
 * 线程交替执行  Produce Consumer 操作同一个变量  num = 0
 * Produce num+1
 * Consumer num-1
 */
public class Syn {
    public static void main(String[] args) {
        Food food = new Food();
        new Thread(()->{for(int i=0;i<10;i++) {
            try {
                food.increment();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        },"生产者").start();

        new Thread(()->{for(int i=0;i<10;i++) {
            try {
                food.decrement();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        },"消费者").start();
    }

}
//判断等待 业务 通知
class Food {
    private int number = 0;

    public synchronized void increment() throws InterruptedException {
        if(number!=0){
            //等待
            this.wait();
        }
        number++;
        System.out.println(Thread.currentThread().getName()+"==>"+number);
        //通知其他线程,我+1完毕了
        this.notifyAll();
    }

    public synchronized void decrement() throws InterruptedException {
        if(number==0){
            //等待
            this.wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName()+"==>"+number);
        //通知其他线程,我+1完毕了
        this.notifyAll();
    }
}

生产者==>1
消费者==>0
生产者==>1
消费者==>0
生产者==>1
消费者==>0
.........

问题存在,A B C D 等多个线程! 虚假唤醒

在这里插入图片描述
解决方法: if 改为 while

package com.zbk.pc;

/**
 * 线程之间的通信问题 : 生产者和消费者问题
 * 线程交替执行  Produce Consumer 操作同一个变量  num = 0
 * Produce num+1
 * Consumer num-1
 */
public class Syn {
    public static void main(String[] args) {
        Food food = new Food();
        new Thread(()->{for(int i=0;i<10;i++) {
            try {
                food.increment();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        },"A").start();

        new Thread(()->{for(int i=0;i<10;i++) {
            try {
                food.decrement();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        },"B").start();
        new Thread(()->{for(int i=0;i<10;i++) {
            try {
                food.decrement();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        },"C").start();
        new Thread(()->{for(int i=0;i<10;i++) {
            try {
                food.increment();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        },"D").start();
    }

}
//判断等待 业务 通知
class Food {
    private int number = 0;

    public synchronized void increment() throws InterruptedException {
        while(number!=0){
            //等待
            this.wait();
        }
        number++;
        System.out.println(Thread.currentThread().getName()+"==>"+number);
        //通知其他线程,我+1完毕了
        this.notifyAll();
    }

    public synchronized void decrement() throws InterruptedException {
        while(number==0){
            //等待
            this.wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName()+"==>"+number);
        //通知其他线程,我+1完毕了
        this.notifyAll();
    }
}

生产者消费者问题 JUC版

在这里插入图片描述

package com.zbk.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程之间的通信问题 : 生产者和消费者问题
 * 线程交替执行  Produce Consumer 操作同一个变量  num = 0
 * Produce num+1
 * Consumer num-1
 */
public class LockPC {
    public static void main(String[] args) {
        Food1 food = new Food1();
        new Thread(()->{for(int i=0;i<10;i++) {
            try {
                food.increment();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        },"A").start();

        new Thread(()->{for(int i=0;i<10;i++) {
            try {
                food.decrement();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        },"B").start();
    }

}

//判断等待 业务 通知
class Food1 {
    private int number = 0;

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public  void increment() throws InterruptedException {
        lock.lock();
        try {
            while(number!=0){
                //等待
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+"==>"+number);
            //通知其他线程,我+1完毕了
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public  void decrement() throws InterruptedException {
        lock.lock();
        try {
            while(number==0){
                //等待
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+"==>"+number);
            //通知其他线程,我-1完毕了
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

Condition 精准的通知和唤醒线程

package com.zbk.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程之间的通信问题 : 生产者和消费者问题
 * 线程交替执行  Produce Consumer 操作同一个变量  num = 0
 * Produce num+1
 * Consumer num-1
 */
public class LockPC {
    public static void main(String[] args) {
        Food1 food = new Food1();
        new Thread(()->{for(int i=0;i<10;i++) {
            try {
                food.increment();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        },"A").start();

        new Thread(()->{for(int i=0;i<10;i++) {
            try {
                food.decrement();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        },"B").start();
    }

}

//判断等待 业务 通知
class Food1 {
    private int number = 0;

    final Lock lock = new ReentrantLock();
    final Condition produce  = lock.newCondition();
    final Condition consumer = lock.newCondition();



    public  void increment() throws InterruptedException {
        lock.lock();
        try {
            while(number!=0){
                //精准通知生产者等待
                produce.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+"==>"+number);
            //精准唤醒消费者
            consumer.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public  void decrement() throws InterruptedException {
        lock.lock();
        try {
            while(number==0){
                //精准通知消费者等待
                consumer.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+"==>"+number);
            //精准唤醒生产者
            produce.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

5. 8锁现象

如何判断锁的是谁!
深刻理解我们的锁

8锁问题

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值