JUC并发编程——学习笔记

正文笔记:

JUC并发编程——学习笔记_第1张图片
JUC并发编程——学习笔记_第2张图片

函数式接口:Thread重写直接lambda操作
JUC并发编程——学习笔记_第3张图片

低耦合:
JUC并发编程——学习笔记_第4张图片
JUC并发编程——学习笔记_第5张图片
JUC并发编程——学习笔记_第6张图片
JUC并发编程——学习笔记_第7张图片
JUC并发编程——学习笔记_第8张图片
JUC并发编程——学习笔记_第9张图片
虚假唤醒解决办法:if判断改为while循环(官方文档)
JUC并发编程——学习笔记_第10张图片
JUC并发编程——学习笔记_第11张图片

锁的研究:
JUC并发编程——学习笔记_第12张图片
JUC并发编程——学习笔记_第13张图片
JUC并发编程——学习笔记_第14张图片
JUC并发编程——学习笔记_第15张图片
JUC并发编程——学习笔记_第16张图片
不安全集合:
JUC并发编程——学习笔记_第17张图片
JUC并发编程——学习笔记_第18张图片

JUC并发编程——学习笔记_第19张图片
callable:
JUC并发编程——学习笔记_第20张图片
JUC并发编程——学习笔记_第21张图片
JUC并发编程——学习笔记_第22张图片

减法计数器
JUC并发编程——学习笔记_第23张图片
JUC并发编程——学习笔记_第24张图片
加法计数器:
JUC并发编程——学习笔记_第25张图片
匿名内部类访问局部变量时需要加final修饰(在jdk8之前)
https://blog.csdn.net/tianjindong0804/article/details/81710268?ops_request_misc=&request_id=&biz_id=102&utm_term=%E5%8C%BF%E5%90%8D%E5%B1%80%E9%83%A8%E7%B1%BB%E8%AE%BF%E9%97%AE%E5%B1%80%E9%83%A8%E5%8F%98%E9%87%8F%E8%A6%81%E5%8A%A0final&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduweb~default-0-81710268.first_rank_v2_pc_rank_v29&spm=1018.2226.3001.4187
pv并发信号量:
JUC并发编程——学习笔记_第26张图片
读写锁:
JUC并发编程——学习笔记_第27张图片
JUC并发编程——学习笔记_第28张图片
JUC并发编程——学习笔记_第29张图片
阻塞队列
JUC并发编程——学习笔记_第30张图片

JUC并发编程——学习笔记_第31张图片
JUC并发编程——学习笔记_第32张图片
JUC并发编程——学习笔记_第33张图片

package juc;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

public class ArrayBlockQueue {
    public static void main(String[] args) throws InterruptedException {
        test4();
    }
    public static void test(){
        ArrayBlockingQueue blockingQueue=new ArrayBlockingQueue<>(3);

        System.out.println(blockingQueue.add("1"));
        System.out.println(blockingQueue.add("2"));
        System.out.println(blockingQueue.add("3"));


        System.out.println("======================");
        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());


    }
    public static void test2(){
        ArrayBlockingQueue blockingQueue=new ArrayBlockingQueue<>(3);

        System.out.println(blockingQueue.offer("1"));
        System.out.println(blockingQueue.offer("2"));
        System.out.println(blockingQueue.offer("3"));


        System.out.println("======================");
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());


    }
    //超时一直等待
    public static void test3() throws InterruptedException {
        ArrayBlockingQueue blockingQueue=new ArrayBlockingQueue<>(3);

        blockingQueue.put("1");
        blockingQueue.put("2");
        blockingQueue.put("3");


        System.out.println("======================");
        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());



    }

    //超时一直等待 超过时间自动退出
    public static void test4() throws InterruptedException {
        ArrayBlockingQueue blockingQueue=new ArrayBlockingQueue<>(3);

        System.out.println(blockingQueue.offer("1"));
        System.out.println(blockingQueue.offer("2"));
        System.out.println(blockingQueue.offer("3"));
        blockingQueue.offer("4",1, TimeUnit.SECONDS);

        System.out.println("======================");
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());


    }
}

SynchronousQueue:
JUC并发编程——学习笔记_第34张图片
线程池:
https://blog.csdn.net/dodod2012/article/details/107464723
JUC并发编程——学习笔记_第35张图片

package juc;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class 线程池 {


    public static void main(String[] args) {

        //ExecutorService T = Executors.newSingleThreadExecutor();
        //ExecutorService T = Executors.newFixedThreadPool(5);
        ExecutorService T = Executors.newCachedThreadPool();


        try {
            for (int i = 0; i < 100; i++) {
                T.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"ok");


                });


            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            T.shutdown();
        }


    }
}

JUC并发编程——学习笔记_第36张图片

自定义线程池
JUC并发编程——学习笔记_第37张图片

package juc;

import java.util.concurrent.*;

public class 线程池 {


    public static void main(String[] args) {

        //ExecutorService T = Executors.newSingleThreadExecutor();
        //ExecutorService T = Executors.newFixedThreadPool(5);
        //ExecutorService T = Executors.newCachedThreadPool();
        ExecutorService threadPool =new ThreadPoolExecutor(
                2,
                5,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );

        try {
            for (int i = 0; i < 3; i++) {
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"ok");


                });


            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            threadPool.shutdown();
        }


    }
}

JUC并发编程——学习笔记_第38张图片
函数式接口
JUC并发编程——学习笔记_第39张图片
JUC并发编程——学习笔记_第40张图片
断定型接口
JUC并发编程——学习笔记_第41张图片
消费型接口
JUC并发编程——学习笔记_第42张图片
供给型接口
JUC并发编程——学习笔记_第43张图片
JUC并发编程——学习笔记_第44张图片

stream流式计算:
比较器接口重写:
https://blog.csdn.net/weixin_37613476/article/details/119249464?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522164169908016780265421672%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=164169908016780265421672&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allfirst_rank_ecpm_v1~rank_v31_ecpm-2-119249464.first_rank_v2_pc_rank_v29&utm_term=compartor%E6%8E%A5%E5%8F%A3%E6%80%8E%E4%B9%88%E9%87%8D%E5%86%99&spm=1018.2226.3001.4187

package juc;

import java.util.Arrays;
import java.util.List;

public class Stream流计算 {

    public static void main(String[] args) {
        User u1=new User(1,"a",23);
        User u2=new User(2,"b",23);
        User u3=new User(3,"c",23);
        User u4=new User(4,"d",23);
        User u5=new User(5,"e",23);


        List<User> list = Arrays.asList(u1,u2,u3,u4,u5);
        list.stream().filter(user -> {return user.getId()%2==0;}).filter(user -> {return user.getAge()>=23;})
                .map(user -> {user.setName(user.getName().toUpperCase());return user;}).limit(1).forEach(System.out::println);
    }






}

自定义sorted排序:
https://blog.csdn.net/zhouzhiwengang/article/details/112312266?ops_request_misc=&request_id=&biz_id=102&utm_term=stream%E6%B5%81%E4%B8%AD%E8%87%AA%E5%AE%9A%E4%B9%89sorted&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduweb~default-2-112312266.first_rank_v2_pc_rank_v29&spm=1018.2226.3001.4187

package juc;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Stream流计算 {

    public static void main(String[] args) {
        User u1=new User(1,"a",23);
        User u2=new User(2,"b",22);
        User u3=new User(3,"c",23);
        User u4=new User(4,"d",26);
        User u5=new User(5,"e",23);


        List<User> list = Arrays.asList(u1,u2,u3,u4,u5);
        list.stream().filter(user -> {return user.getId()%2==0;}).filter(user -> {return user.getAge()>=2;})
                .map(user -> {user.setName(user.getName().toUpperCase());return user;}).sorted(Comparator.comparing(User::getAge).reversed()).limit(3).forEach(System.out::println);
    }






}

异步调用:
JUC并发编程——学习笔记_第45张图片

JUC并发编程——学习笔记_第46张图片

package juc;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class 异步 {


    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        CompletableFuture voidCompletableFuture = CompletableFuture.runAsync(() -> {
//            try {
//                TimeUnit.SECONDS.sleep(2);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            System.out.println(Thread.currentThread().getName()+"void");
//        });
//        voidCompletableFuture.get();//他会在这里阻塞 这个顺序很重要
//        System.out.println("11111");


        CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "Integer");
            int i=10/0;
            return 1024;
        });

        System.out.println(integerCompletableFuture.whenComplete((t,u)->{
            System.out.println(t);
            System.out.println(u);
        }).exceptionally((e)->{
            System.out.println(e.getMessage());
            return 233;
        }).get()); //拿到最终结果


        System.out.println("111111");
    }
}

JMM:
JUC并发编程——学习笔记_第47张图片
JUC并发编程——学习笔记_第48张图片

多线程的执行顺序问题:
https://blog.csdn.net/weixin_41799019/article/details/100172513?spm=1001.2101.3001.6650.6&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-6.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-6.no_search_link&utm_relevant_index=8
异步与多线程:
https://blog.csdn.net/kxkxyzyz/article/details/104775488?ops_request_misc=&request_id=&biz_id=102&utm_term=%E5%A4%9A%E7%BA%BF%E7%A8%8B%E5%BC%82%E6%AD%A5%E6%97%B6%E5%A6%82%E6%9E%9C%E6%B2%A1%E6%89%A7%E8%A1%8C%E5%AE%8C%E4%BC%9A%E9%98%BB%E5%A1%9E%E5%90%97&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduweb~default-4-104775488.first_rank_v2_pc_rank_v29&spm=1018.2226.3001.4187

volatile:

1 可见性:

package juc;

import java.sql.Timestamp;
import java.util.concurrent.TimeUnit;

public class JMM {


    private volatile static int num=0;
  
    public static void main(String[] args) {
        new Thread(()->{
            while (num==0){

            }
        }).start();


        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        num=1;
        System.out.println(num);

    }



}

2 非原子性:(可以使用lock和synchronized实现 或者使用原子类)

package juc;

public class Volitile {


    private volatile static int num;

    private synchronized static void add(){
        num++;
    }

    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                for (int i1 = 0; i1 < 100; i1++) {
                    add();
                }
            }).start();
        }


        while (Thread.activeCount()>2){
            Thread.yield();
        }
        System.out.println(num);




    }
}

package juc;

import java.util.concurrent.atomic.AtomicInteger;

public class Volitile {


    private  static AtomicInteger num=new AtomicInteger();

    private synchronized static void add(){
        num.incrementAndGet();
    }

    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                for (int i1 = 0; i1 < 100; i1++) {
                    add();
                }
            }).start();
        }


        while (Thread.activeCount()>2){ //很关键
            Thread.yield();
        }
        System.out.println(num);




    }
}

3 避免指令重排
JUC并发编程——学习笔记_第49张图片
JUC并发编程——学习笔记_第50张图片
单例模式:
JUC并发编程——学习笔记_第51张图片
JUC并发编程——学习笔记_第52张图片
JUC并发编程——学习笔记_第53张图片
JUC并发编程——学习笔记_第54张图片

JUC并发编程——学习笔记_第55张图片
(防止指令重排 所以要加voliatile,因为不然1 3 2的话 分配空间了但还没完成构造 这个时候多线程b进来 发现lazyman已经有指向了 那么他就直接返回了 但是他没有完成构造 所以 1 2 3 才是最安全的指令顺序)
JUC并发编程——学习笔记_第56张图片

JUC并发编程——学习笔记_第57张图片
JUC并发编程——学习笔记_第58张图片

JUC并发编程——学习笔记_第59张图片
代码:

package juc;

public enum enumsigle {
    INSTANCE;

    public enumsigle getInstance(){
        return INSTANCE;
    }
}
class Text{
    public static void main(String[] args) {
        enumsigle instance=enumsigle.INSTANCE;
        enumsigle instance2=enumsigle.INSTANCE;

        System.out.println(instance);
        System.out.println(instance2);

    }
}

package juc;

public class 单例模式Hungury {

    private byte[] data1=new byte[1024*1024];
    private byte[] data2=new byte[1024*1024];
    private byte[] data3=new byte[1024*1024];
    private byte[] data4=new byte[1024*1024];

    private 单例模式Hungury(){

    }

    private final static 单例模式Hungury HUNGURY=new 单例模式Hungury();

    public static 单例模式Hungury getInstance(){
        return HUNGURY;
    }





}

package juc;

import javafx.scene.control.Label;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class LazyMan {
//双重锁效率高 不然直接静态方法加锁类锁也许 效率低一些 锁的资源越小越好
//    private LazyMan(){
//
//    }
//    private LazyMan(){
//        synchronized (LazyMan.class){
//            if(lazyMan!=null){
//                throw new RuntimeException("不要试图反射"); //但他可以直接反射创建两个 也可以破解
//            }
//        }
//    }
    public static boolean gx=false;
    private LazyMan(){
        if(gx==false){
            gx=true;

        }else {
            throw new RuntimeException("不要创建两个对象反射");
        }
    }
    private volatile static LazyMan lazyMan;

    public static LazyMan getInstance(){
        if(lazyMan==null){
            synchronized (LazyMan.class){
                if(lazyMan==null){
                    lazyMan=new LazyMan();
                }
            }
        }
        return lazyMan;
    }

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        //LazyMan instance=LazyMan.getInstance();

        Constructor<LazyMan> declared=LazyMan.class.getDeclaredConstructor(null);
        declared.setAccessible(true);

        Field gx = LazyMan.class.getDeclaredField("gx");
        gx.setAccessible(true);
        LazyMan instance2=declared.newInstance();

        gx.set(instance2,false);
        LazyMan instance3=declared.newInstance();
        //System.out.println(instance);
        System.out.println(instance2);
        System.out.println(instance3);

    }


}

CAS:
JUC并发编程——学习笔记_第60张图片
JUC并发编程——学习笔记_第61张图片
JUC并发编程——学习笔记_第62张图片
在这里插入图片描述
JUC并发编程——学习笔记_第63张图片
JUC并发编程——学习笔记_第64张图片
在这里插入图片描述
原子引用:

JUC并发编程——学习笔记_第65张图片
JUC并发编程——学习笔记_第66张图片
JUC并发编程——学习笔记_第67张图片
JUC并发编程——学习笔记_第68张图片

各种锁:
JUC并发编程——学习笔记_第69张图片
在这里插入图片描述
(锁一定要配对)

自旋锁:
JUC并发编程——学习笔记_第70张图片
死锁:
JUC并发编程——学习笔记_第71张图片
JUC并发编程——学习笔记_第72张图片
JUC并发编程——学习笔记_第73张图片
JUC并发编程——学习笔记_第74张图片

package juc;

import java.util.concurrent.TimeUnit;

public class 死锁 {
    public static void main(String[] args) {
        String lock1="lock1";
        String lock2="lock2";

        new Thread(new Mythread(lock1,lock2)).start();
        new Thread(new Mythread(lock2,lock1)).start();
    }


}
class Mythread implements Runnable {

    String lockA;
    String lockB;

    public Mythread(String lockA,String lockB){
        this.lockA=lockA;
        this.lockB=lockB;
    }
    @Override
    public void run() {
        synchronized (lockA){
            System.out.println("拿到了A字符串"+Thread.currentThread().getName());

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lockB){
                System.out.println("拿到了B字符串"+Thread.currentThread().getName());
            }
        }


    }
}

你可能感兴趣的:(java多线程,juc,java)