JUC编程(java.util.concurrent)

本视频看的是狂神的JUC

什么是Juc?

在这里插入图片描述

JUI的并发编程

业务:普通的线程代码类Thread, Runnable接口,没有返回值,相比Callable效率低,所以企业的开发中使用Callable接口多.

Lock?

java.util.current.Lock 包括ReetrantLock,ReetrantReadWriteLock

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nkbEAuMH-1639027859900)(C:\Users\CourageAndLove\AppData\Roaming\Typora\typora-user-images\image-20211207134110414.png)]

进程和线程的区别?

进程:一个程序 QQ.exe,.jar,包含多个线程

一个java程序默认几个线程?2个

java真的可以开启线程吗?不可以,看它的方法知道它只可以通过调用start0方法操作,底层通过c++来进行操作硬件。

   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 */
            }
        }
    }

    private native void start0();

并发并行的区别?

并发多个线程操作同一资源。

并行:cpu多核,多个线程同时执行

JUC并发编程的目的:充分利用CPU的资源。

线程的状态

线程的状态源码

public enum State {
    
    
    /**
     * Thread state for a thread which has not yet started.
     */
    //
    NEW, 

    /**
     * Thread state for a runnable thread.  A thread in the runnable
     * state is executing in the Java virtual machine but it may
     * be waiting for other resources from the operating system
     * such as processor.
     */
    RUNNABLE,

    /**
     * Thread state for a thread blocked waiting for a monitor lock.
     * A thread in the blocked state is waiting for a monitor lock
     * to enter a synchronized block/method or
     * reenter a synchronized block/method after calling
     * {@link Object#wait() Object.wait}.
     */
    BLOCKED,

    /**
     * Thread state for a waiting thread.
     * A thread is in the waiting state due to calling one of the
     * following methods:
     * <ul>
     *   <li>{@link Object#wait() Object.wait} with no timeout</li>
     *   <li>{@link #join() Thread.join} with no timeout</li>
     *   <li>{@link LockSupport#park() LockSupport.park}</li>
     * </ul>
     *
     * <p>A thread in the waiting state is waiting for another thread to
     * perform a particular action.
     *
     * For example, a thread that has called <tt>Object.wait()</tt>
     * on an object is waiting for another thread to call
     * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
     * that object. A thread that has called <tt>Thread.join()</tt>
     * is waiting for a specified thread to terminate.
     */
    //等待(没有时间的限制的等待)
    WAITING,

    /**
     * Thread state for a waiting thread with a specified waiting time.
     * A thread is in the timed waiting state due to calling one of
     * the following methods with a specified positive waiting time:
     * <ul>
     *   <li>{@link #sleep Thread.sleep}</li>
     *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
     *   <li>{@link #join(long) Thread.join} with timeout</li>
     *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
     *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
     * </ul>
     */
    //超时等待(会有时间的限制)
    TIMED_WAITING,

    /**
     * Thread state for a terminated thread.
     * The thread has completed execution.
     */
    //终止
    TERMINATED;
}

wait/sleep 区别

来自不同的类

wait =>Object

sleep => Thread

企业中的休眠会用sleep的吗?不会,一般使用`

import java.util.concurrent.TimeUnit;
  TimeUnit.DAYS.sleep(1);

2.关于锁的释放

wait :会释放锁 (不需要捕获异常)

等待的条件必须在同步代码块中。

sleep: 睡觉了,抱着睡觉,不会释放!(需要捕获异常)

Lock锁的详细讲解(important)

synchronized和Lock锁的区别

  1. sychronized是内置java关键字,Lock是一个java类(接口)
  2. sychronized适合锁少量的代码,Lock适合大量的代码
  3. sychronized 无法判断锁的状态,Lock可以获取锁的状态。
  4. sychronized 会自动释放锁,Lock需要手动关闭锁!,如果不释放会产生死锁。
  5. 线程1(获取锁,阻塞)线程2(等待、傻傻的等待),Lock锁就不一定等待下去。
  6. sychronized 可重入锁,不可以中断的,非公平 Lock,可以重入锁,可以判断锁,公平或者不公平可以手动的设置。

sychronized实现并发处理:

package com.hou.demo;
/*
* 真正的多线程开发,
* 企业开发,线程是一个单独的资源类,没有任何的附属操作
* 1. 属性方法
* */
public class SaleTicketDemo01 {
    
    
    public static void main(String[] args) {
    
    
//        new Thread(new MyThread()).start();


//        并发:多线程操作同一个资源类,把资源类丢入线程

//        @FunctionalInterface 函数式接口,jdk1.8 lamda表达式
        final Ticket ticket=new Ticket();
//这个是通过匿名函数进行实现的
/*        new Thread(new Runnable() {
            @Override
            public void run() {

            }
        }).start();*/
//lamda表达式的()为传入的参数的名称,{}写入你的代码,后面的”A"为你的线程的名字
        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();
    }




   /* 企业不会用这个开发性能低
   static class MyThread implements  Runnable{

        @Override
        public void run() {

        }
    }*/

//    资源类oop
static class Ticket{
    
    
        private  Integer num=20;

//        卖票的方式  传统的synchronized可以解决这个高并发的问题
        public synchronized void sale(){
    
    
            if(num>0) {
    
    
                System.out.println(Thread.currentThread().getName()+"卖出了"+(num-num)+"票,剩余:"+(num--));
            }
        }







}
}

Lock锁实现并发处理:

1. new RreentrantLock

2. try{lock.lock(); //锁定的方法}catch{}

3.进行锁的释放(lock.unlock())

4. 代码实现如下所示:

package com.hou.demo;
/*
* 真正的多线程开发,
* 企业开发,线程是一个单独的资源类,没有任何的附属操作
* 1. 属性方法
* */
public class SaleTicketDemo01 {
    
    
    public static void main(String[] args) {
    
    
//        new Thread(new MyThread()).start();


//        并发:多线程操作同一个资源类,把资源类丢入线程

//        @FunctionalInterface 函数式接口,jdk1.8 lamda表达式
        final Ticket ticket=new Ticket();
//这个是通过匿名函数进行实现的
/*        new Thread(new Runnable() {
            @Override
            public void run() {

            }
        }).start();*/
//lamda表达式的()为传入的参数的名称,{}写入你的代码,后面的”A"为你的线程的名字
        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();
    }




   /* 企业不会用这个开发性能低
   static class MyThread implements  Runnable{

        @Override
        public void run() {

        }
    }*/

//    资源类oop
static class Ticket{
    
    
        private  Integer num=20;

//        卖票的方式  传统的synchronized可以解决这个高并发的问题
        public synchronized void sale(){
    
    
            if(num>0) {
    
    
                System.out.println(Thread.currentThread().getName()+"卖出了"+(num-num)+"票,剩余:"+(num--));
            }
        }

}
}

生产者消费者sychronized版本

生产者消费者sychronized版本

·代码实现如下:

package pc;

// 线程交替执行 A B 操作同一个变量
public class ATest {
    
    
    public static void main(String[] args) {
    
    
        Data data = new Data();
       new Thread(()->{
    
    
           try {
    
    
               for (int i = 0; i < 5; i++) {
    
    
                   data.increment();
               }

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

            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        },"B").start();

        new Thread(()->{
    
    
            try {
    
    
                for (int i = 0; i < 5; i++) {
    
    
                    data.increment();
                }

            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        },"C").start();

        new Thread(()->{
    
    
            try {
    
    
                for (int i = 0; i < 5; i++) {
    
    
                    data.decrement();
                }

            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        },"D").start();


    }

// 判断等待,业务, 通知
static class Data{
    
     //数字   资源类
        private  int number = 0;
//    +1
    public synchronized  void increment() throws InterruptedException {
    
    
//       需要把if变为while    防止虚假唤醒
        while (number!=0) {
    
    
//            等待
            this.wait();
        }

        number++;
        System.out.println(Thread.currentThread().getName() + "=>" + number);
//        通知线程其他线程,我+1完毕了
        this.notifyAll();


    }
//    -1
    public synchronized void decrement() throws InterruptedException {
    
    
       while(number==0){
    
    
            //等待
            this.wait();
        }

        number--;
        System.out.println(Thread.currentThread().getName() + "=>" + number);
//        通知其他的线程,我-1完毕了
        this.notifyAll();

    }

    }
}


生产者消费者Lock版本

lock版本

在这里插入图片描述

代码实现如下:

package com.hou.demo;

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

/*
* 真正的多线程开发,
* 企业开发,线程是一个单独的资源类,没有任何的附属操作
* 1. 属性方法
* */
public class SaleTicketDemo02 {
    
    
    public static void main(String[] args) {
    
    




        Ticket ticket=new Ticket();

//lamda表达式的()为传入的参数的名称,{}写入你的代码,后面的”A"为你的线程的名字
        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
static class Ticket{
    
    
        private  Integer num=20;
        int i=0;
        Lock lock=new ReentrantLock();    //它的实现类有ReentrantLock,ReadLock


        public  void sale(){
    
    
            lock.lock();
            try {
    
    
                if(num>0) {
    
    
                    System.out.println(Thread.currentThread().getName()+"卖出了"+(i++)+"票,剩余:"+(num--));
                }
            }catch (Exception e){
    
    
                lock.unlock();//解锁
               e.printStackTrace();
            }

        }

}
}

防止虚假唤醒把其中的if变为while实现

在这里插入图片描述

Condition可以做到精准通知和唤醒线程 也就是可以让线程有序的执行

在这里插入图片描述

代码如下:

package pc;

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

public class ConditionTest {
    
    
    public static void main(String[] args) {
    
    
        Data3 data3 = new Data3();

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

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

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


    }




//    使用Condition实现精准通知
static class Data3{
    
    
        private int num=1; //num为1让A执行 2让B执行 3C
        Lock lock=new ReentrantLock();
        private Condition condition1= lock.newCondition();
        private Condition condition2 = lock.newCondition();
        private Condition condition3 = lock.newCondition();

        public void print1() throws InterruptedException {
    
    
            try {
    
    
                lock.lock();
                while (num!=1){
    
    
//                    等待
                    condition1.await();

                }
                num=2;
                System.out.println(Thread.currentThread().getName() + "=>AAAAAAAA");
                //唤醒B
                condition2.signal();

            } catch (Exception e) {
    
    

                e.printStackTrace();
            } finally {
    
    

                lock.unlock();
            }


        }
        public void print2() throws InterruptedException {
    
    
            try {
    
    
                lock.lock();
                while (num!=2){
    
    
//                    等待
                    condition2.await();

                }
                num=3;
                System.out.println(Thread.currentThread().getName() + "=>BBBBBBBB");
                //唤醒B
                condition3.signal();
            } catch (Exception e) {
    
    

                e.printStackTrace();
            } finally {
    
    

                lock.unlock();
            }




        }
        public void print3() throws InterruptedException{
    
    
            try {
    
    
                lock.lock();
                while (num!=3){
    
    
                    condition3.await();
                }
                num=1;
                System.out.println(Thread.currentThread().getName() + "=>CCCCCCCCCCCCC");
                condition1.signal();
            } catch (Exception e) {
    
    
                e.printStackTrace();
            } finally {
    
    
                lock.unlock();
            }


        }
    }
}

猜你喜欢

转载自blog.csdn.net/houzhicongone/article/details/121817496