JUC编程(java.util.concurrent)

Posted houzhicongone

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JUC编程(java.util.concurrent)相关的知识,希望对你有一定的参考价值。

本视频看的是狂神的JUC

什么是Juc?

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

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. trylock.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--));
            
        



以上是关于JUC编程(java.util.concurrent)的主要内容,如果未能解决你的问题,请参考以下文章

JUC 高并发编程

JUC并发编程总结复盘

尚硅谷JUC高并发编程学习笔记JUC简介与Lock接口

尚硅谷JUC高并发编程学习笔记JUC简介与Lock接口

Java并发编程系列之三JUC概述

juc多线程编程学习