十、JUC并发编程【面试高频问】

1.什么是JUC?

在这里插入图片描述
java.util 工具包、包、分类
Runnable没有返回值,效率比Callable低
在这里插入图片描述
在这里插入图片描述

2. 线程和进程

线程、进程
1.进程:程序的集合;
一个进程往往可以包含多个线程,至少包含一个
2.Java默认有几个进程?2个
main线程、GC线程
3.对于Java而言开启线程的方式:Thread、Runnable、Callable
4.Java真的可以开启线程吗?
不可以,只能通过本地方法去调,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 */
            }
        }
    }
//本地方法,调用底层C++,Java无法直接操作硬件
    private native void start0();

并发与并行
并发:多线程操作同一个资源

  • CPU一核,模拟出多线程,通过线程快速交替

并行:多个人一起行走

  • CPU多核,多个线程可以同时执行;线程池
    查看电脑线程数
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 可以在任何地方睡
4.是否需要捕获异常
wait 不需要捕获异常
sleep 需要捕获异常

3.Lock锁(重点)

传统的 Synchronized

public class SaleTicketDemo01 {
   
    public static void main(String[] args) {
   
        //并发:多个线程操作同一个资源类
        Ticket ticket = new Ticket();
        //Runnable接口是一个函数式接口,匿名内部类,简化写法,使用lambda表达式  ()-> {}
        new Thread(() -> {
   
            for (int i = 0; i < 60; i++) {
   
                ticket.sale();
            }
        },"A").start();
        new Thread(() -> {
   
            for (int i = 0; i < 60; i++) {
   
                ticket.sale();
            }
        },"B").start();
        new Thread(() -> {
   
            for (int i = 0; i < 60; i++) {
   
                ticket.sale();
            }
        },"C").start();
    }
}
//资源类 OOP
class Ticket{
   
    //属性 方法
    private int number = 30;
    //卖票的方式
    // synchronized 本质:队列、锁
    public synchronized void sale(){
   
        if(number > 0){
   
            System.out.println(Thread.currentThread().getName()+"卖出了第"+(number--)+"张票,剩余:"+number);
        }
    }
}

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

public class SaleTicketDemo02 {
   
    public static void main(String[] args) {
   
        //并发:多个线程操作同一个资源类
        Ticket2 ticket = new Ticket2();
        new Thread(() -> {
   
            for (int i = 0; i < 60; i++) {
   
                ticket.sale();
            }
        },"A").start();
        new Thread(() -> {
   
            for (int i = 0; i < 60; i++) {
   
                ticket.sale();
            }
        },"B").start();
        new Thread(() -> {
   
            for (int i = 0; i < 60; i++) {
   
                ticket.sale();
            }
        },"C").start();
    }
}
//Lock三部曲
//1.new ReentrantLock
//2.lock.lock();//加锁
//3.解锁 finally中 lock.unlock();

class Ticket2{
   
    //属性 方法
    private int number = 30;
    //卖票的方式
    // synchronized 本质:队列、锁
    Lock lock = new ReentrantLock();
    public void sale(){
   
        lock.lock();//加锁
        try {
   
            //业务代码
            if(number > 0){
   
                System.out.println(Thread.currentThread().getName()+"卖出了第"+(number--)+"张票,剩余:"+number);
            }
        } finally {
   
            //解锁
            lock.unlock();
        }
    }
}

Synchronized 和 Lock锁的区别
1.Synchronized 是内置的java关键字,Lock 是一个java类
2.Synchronized 无法判断获取锁的状态,Lock 可以判断是否获取到了锁
3.Synchronized 会自动释放锁,Lock 必须要手动释放锁!如果不释放锁,会产生死锁
4.Synchronized 线程1(获得锁,阻塞)、线程2(等待,傻傻地等待)
Lock 锁就不一定等待下去【因为Lock 有lock.tryLock();方法,尝试获取锁】
5.Synchronized 可重入锁,不可以中断,非公平;Lock ,可重入锁,可以判断锁,非公平(可以自己设置)
6.Synchronized 适合锁少量的代码同步问题,Lock锁适合锁大量的同步代码
锁是什么,如何判断锁的是谁

4.生产者和消费者问题

生产者和消费者问题 Synchronized版

public class A {
   
    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();
                }
            }
        },"A").start();
        new Thread(() -> {
   
            for (int i = 0; i < 10; i++) {
   
                try {
   
                    data.decrement();
                } catch (InterruptedException e) {
   
                    e.printStackTrace();
                }
            }
        },"B").start();
    }
}
//等待 业务 通知
class Data{
   
    private int number = 0;
    //+1
    public synchronized void increment() throws InterruptedException {
   
        if(number != 0){
   
            this.wait();//等待
        }
        number++;
        System.out.println(Thread.currentThread().getName() + " =>" + number);
        //通知其他线程
        this.notifyAll();
    }
    //-1
    public synchronized void decrement() throws InterruptedException {
   
        if(number == 0){
   
            this.wait();
            //等待
        }
        number--;
        System.out.println(Thread.currentThread().getName() + " =>" + number);
        //通知其他线程
        this.notifyAll();
    }
}

问题存在,A、B、C、D四个线程,两个加一,两个减一,会出现问题【会出现值为2或3的情况】
在这里插入图片描述

在这里插入图片描述
将if改成while循环
if判断进去不会停,while判断,一个被修改,如果另一个拿到手了,就在这个地方进行等待,防止虚假唤醒发生

防止虚假唤醒

public class A {
   
    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();
                }
            }
        },"A").start();
        new Thread(() -> {
   
            for (int i = 0; i < 10; i++) {
   
                try {
   
                    data.decrement();
                } catch (InterruptedException e) {
   
                    e.printStackTrace();
                }
            }
        },"B").start();
        new Thread(() -> {
   
            for (int i = 0; i < 10; i++) {
   
                try {
   
                    data.increment();
                } catch (InterruptedException e) {
   
                    e.printStackTrace();
                }
            }
        },"C").start();
        new Thread(() -> {
   
            for (int i = 0; i < 10; i++) {
   
                try {
   
                    data.decrement();
                } catch (InterruptedException e) {
   
                    e.printStackTrace();
                }
            }
        },"D").start();

    }
}
//等待 业务 通知
class Data{
   
    private int number = 0;
    //+1
    public synchronized void increment() throws InterruptedException {
   
        while (number != 0){
   
            this.wait();//等待
        }
        number++;
        System.out.println(Thread.currentThread().getName() + " =>" + number);
        //通知其他线程
        this.notifyAll();
    }
    //-1
    public synchronized void decrement() throws InterruptedException {
   
        while (number == 0){
   
            this.wait();
            //等待
        }
        number--;
        System.out.println(Thread.currentThread().getName() + " =>" + number);
        //通知其他线程
        this.notifyAll();
    }
}

JUC版的生产者与消费者
在这里插入图片描述
在这里插入图片描述
代码实现:

public class B {
   
    public static void main(String[] args) {
   
        Data2 data2 = new Data2();
        new Thread(()->{
   
            for (int i = 0; i < 10; i++) {
   
                try {
   
                    data2.increment();
                } catch (InterruptedException e) {
   
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()->{
   
            for (int i = 0; i < 10; i++) {
   
                try {
   
                    data2.decrement();
                } catch (InterruptedException e) {
   
                    e.printStackTrace();
                }
            }
        },"B").start();
        new Thread(()->{
   
            for (int i = 0; i < 10; i++) {
   
                try {
   
                    data2.increment();
                } catch (InterruptedException e) {
   
                    e.printStackTrace();
                }
            }
        },
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值