首页 > 编程语言 >JUC并发编程

JUC并发编程

时间:2023-09-11 16:56:39浏览次数:50  
标签:JUC Thread 编程 System 并发 println new public out

JUC并发编程

1.什么是JUC

image-20230815112611571

java.util 工具包,包,分类

业务: 普通的线程代码 Thread

Runable 没有返回值,效率相比Callable相对较低!

image-20230815113246612

image-20230815113420662

2.线程和进程

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

进程:一个程序,例如 qq.exe,代表一个程序的集合

一个进程往往包含多个线程,而一个进程至少包含一个!

java的默认有几个线程?

2个,main主线程和GC垃圾回收线程

线程:开了一个进程Typora,写字,保存->(线程负责的)

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

	//本地方法,底层为C++,Java操作虚拟机无法直接操作硬件
    private native void start0();

并发和并行

并发编程:并发和并行

并发(多线程操作同意资源)

  • CPU一核,模拟出来多条线程,天下武功,唯快不破,快速交替执行

并行(多个人一起行走)

  • CPU多核,多个线程同时进行;多核利用线程池进行操作
package com.landu;

public class demo01 {
    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也需要捕获异常

5.是否需要被唤醒

wait需要被唤醒,而sleep不用被唤醒

3.Lock锁(重点)

传统 Synchronized同步锁

package com.landu.demo01;

//基本地卖票例子

/**
 * 线程就是一个单独的资源类,没有任何附属的操作!
 * 1.属性和方法
 */
public class SaleTicketDemo01 {

    public static void main(String[] args) {
        //并发:多线程操作同一个资源类,把资源类丢入线程
        Ticket ticket = new Ticket();

        //@FunctionalInterface 函数式接口,在jdk1.8 Lambda表达式(参数)->{代码}
        new Thread(() -> {
            for (int i = 1; i < 40; i++) {
                ticket.sale();
            }
        },"A").start();
        new Thread(() -> {
            for (int i = 1; i < 40; i++) {
                ticket.sale();
            }
        },"B").start();
        new Thread(() -> {
            for (int i = 1; i < 40; i++) {
                ticket.sale();
            }
        },"C").start();

    }
}

//资源类 OOP思想
/**
 * synchronized
 */
class Ticket {

    //属性和方法
    private int number = 50;

    //卖票的方式
    public synchronized void sale() {
        if (number > 0) {
            System.out.println(Thread.currentThread().getName()
                    + "卖出了" + (number--) + "票,剩余" + number);
        }
    }
}

Lock接口

image-20230815143002187

image-20230815143051933

image-20230815143732905

公平锁:十分公平,可以是先来后到

非公平锁:十分不公平,可以插队(默认为非公平锁)

package com.landu.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();

        //@FunctionalInterface 函数式接口,在jdk1.8 Lambda表达式(参数)->{代码}
        new Thread(() -> {
            for (int i = 1; i < 40; i++) {
                ticket.sale();
            }
        },"A").start();
        new Thread(() -> {
            for (int i = 1; i < 40; i++) {
                ticket.sale();
            }
        },"B").start();
        new Thread(() -> {
            for (int i = 1; i < 40; i++) {
                ticket.sale();
            }
        },"C").start();

    }
}

//资源类 OOP思想

/**
 * Lock锁三部曲
 * 1.new ReentrantLock();创建锁
 * 2.lock.lock(); //加锁
 * 3.lock.unlock(); //解锁
 */
class Ticket2 {

    //属性和方法
    private int number = 50;

    Lock lock = new ReentrantLock(); //创建锁

    //卖票的方式
    public void sale() {
        lock.lock(); //加锁
        try {
            //业务代码
            if (number > 0) {
                System.out.println(Thread.currentThread().getName()
                        + "卖出了" + (number--) + "票,剩余" + 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锁不一定会一直等待
  5. Synchronized是可重入锁,不可以中断,非公平锁;Lock锁,可重入锁,可以判断锁,非公平(可以自己设置)
  6. Synchronized适合锁少量的同步代码块,相反Lock锁适合锁大量的同步代码块!

锁是什么?如何判断锁的是谁?

4.生产者和消费者问题

生产者和消费者Synchronized版本

package com.landu.pc;

/**
 * 线程之间的通信问题:生产者和消费者问题! 等待唤醒,通知唤醒
 * 线程交替执行 A B 操作同一个变量 num=0
 * A num+1
 * B num-1
 */
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) {
                    throw new RuntimeException(e);
                }
            }
        },"A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"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 4个线程,会产生虚假唤醒

image-20230815162922816

解决方案:把if语句改为while循环,在循环体内进行判断,保证线程同一时间只能访问同一个资源,不会产出抢占资源的情况

while (number != 0) {
            //等待
            this.wait();
        }
while (number == 0) {
            //等待
            this.wait();
        }

Lock版生产者和消费者

传统与JUC的对比

image-20230815164943744

image-20230815164338190

package com.landu.pc;

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

public class B {

    public static void main(String[] args) {
        Data2 data = new Data2();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"A").start();

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

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"C").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"D").start();
    }
}

//判断等待,业务,通知
class Data2 {

    private int number = 0;

    Lock lock = new ReentrantLock();
    //监视器的作用
    Condition condition = lock.newCondition();
    //+1操作
    public  void increment() throws InterruptedException {
        lock.lock();
        try {
            while (number != 0) {
                //等待
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+"=>"+number);
            //通知其他线程
            condition.signalAll();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    //-1操作
    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            while (number == 0) {
                //等待
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+"=>"+number);
            //通知其他线程
            condition.signalAll();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}

任何一个新技术的产生,不仅仅是为了解决原技术无法解决的问题,更多的是技术自身的优势和补充

Condition 精准的通知和唤醒线程

image-20230815170522481

代码测试:

package com.landu.pc;

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

/**
 * A执行完调用B,B执行完调用C,C执行完调用A
 */
public class C {

    public static void main(String[] args) {
        Data3 data3 = new Data3();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data3.printA();
            }
        },"A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data3.printB();
            }
        },"B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data3.printC();
            }
        },"C").start();
    }
}

class Data3 {
    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    private int number = 1;
    public void printA() {
        lock.lock();
        try {
            //业务,判断->执行->通知
            while (number != 1) {
                //等待
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName() + "AAAA");
            number = 2;
            //A执行完唤醒B
            condition2.signal();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }

    }
    public void printB() {
        lock.lock();
        try {
            //业务,判断->执行->通知
            while (number != 2) {
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName() + "BBBB");
            number = 3;
            //B执行完,唤醒C
            condition3.signal();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
    public void printC() {
        lock.lock();
        try {
            //业务,判断->执行->通知
            while (number != 3) {
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName() + "CCCC");
            number = 1;
            //C执行完,唤醒A
            condition1.signal();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}

5.8锁现象

如何判断锁的是谁?为什么会产生锁的概念?

new出来的对象,Class模板

package com.landu.lock8;

import java.util.concurrent.TimeUnit;

/**
 * 1.标志情况下,先输出发短信还是打电话? 1.发短信 2.打电话
 * 2.发短信延迟4s,先输出发短信还是打电话? 1.发短信 2.打电话
 */
@SuppressWarnings("all")
public class Test1 {

    public static void main(String[] args) {
        Phone phone = new Phone();

        new Thread(()->{
            phone.sendMessage();
        },"A").start();

        //休息一秒
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        new Thread(()->{
            phone.call();
        },"B").start();
    }
}

class Phone {

    /**
     * synchronized 锁的对象是方法的调用者,
     * 两个方法用的是同一个锁,谁先拿到谁先执行
     */
    public synchronized void sendMessage() {
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("发短信");
    }

    public synchronized void call() {
        System.out.println("打电话");
    }
}
package com.landu.lock8;

import java.util.concurrent.TimeUnit;

/**
 * 3.增加一个普通方法,先执行hello还是发短信? 1.hello 2.发短信
 * 4.两个对象,两个同步方法,先执行打电话还是发短信? 1.打电话 2.发短信
 */
@SuppressWarnings("all")
public class Test2 {

    public static void main(String[] args) {
        //两个对象,两把锁,两个调用者
        Phone2 phone1 = new Phone2();
        Phone2 phone2 = new Phone2();

        new Thread(()->{
            phone1.sendMessage();
        },"A").start();

        //休息一秒
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        new Thread(()->{
            phone2.call();
        },"B").start();
    }
}

class Phone2 {

    /**
     * synchronized 锁的对象是方法的调用者,
     * 两个方法用的是同一个锁,谁先拿到谁先执行
     */
    public synchronized void sendMessage() {
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("发短信");
    }

    public synchronized void call() {
        System.out.println("打电话");
    }

    //hello方法没有加锁,不会受到锁的影响
    public void hello() {
        System.out.println("hello");
    }
}
package com.landu.lock8;

import java.util.concurrent.TimeUnit;


/**
 * 5.增加两个静态的方法,只有一个对象,先打印发短信还是打电话? 1.发短信 2.打电话
 * 6.两个对象,增加两个静态的方法,先打印发短信还是打电话? 1.发短信 2.打电话
 */
@SuppressWarnings("all")
public class Test3 {

    public static void main(String[] args) {

        //两个对象的Class类模板只有一个,static锁的是Class
        Phone3 phone1 = new Phone3();
        Phone3 phone2 = new Phone3();

        new Thread(()->{
            phone1.sendMessage();
        },"A").start();

        //休息一秒
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        new Thread(()->{
            phone2.call();
        },"B").start();
    }
}

class Phone3 {

    /**
     * synchronized 锁的对象是方法的调用者,
     * static 是静态方法,在类一加载的时候就有了,锁的是Class模板Phone3.class
     * Class<Phone3> phone3Class = Phone3.class;
     */
    public static synchronized void sendMessage() {
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("发短信");
    }

    public static synchronized void call() {
        System.out.println("打电话");
    }
}
package com.landu.lock8;

import java.util.concurrent.TimeUnit;

/**
 *7.一个是静态同步方法发短信,一个是同步方法打电话,先打印哪一个?1.打电话 2.发短信
 * 8.一个是静态同步方法发短信,一个是同步方法打电话,两个对象,先打印哪一个?1.打电话 2.发短信
 */
@SuppressWarnings(value = "all")
public class Test4 {

    public static void main(String[] args) {
        Phone4 phone1 = new Phone4();
        Phone4 phone2 = new Phone4();

        new Thread(()->{
            phone1.sendMessage();
        },"A").start();

        //休息一秒
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        new Thread(()->{
            phone2.call();
        },"B").start();
    }
}

class Phone4 {


    //静态的同步方法,static锁的是class模板
    public static synchronized void sendMessage() {
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("发短信");
    }

    //普通的同步方法,锁的是方法的调用者
    public  synchronized void call() {
        System.out.println("打电话");
    }
}

小结

new 指的是一个具体的对象,而static锁的是一个class模板

6.集合类不安全

List集合不安全

image-20230816161028510

package com.landu.unsafe;

import java.io.Serializable;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

@SuppressWarnings("all")
//java.util.ConcurrentModificationException 线程并发异常
public class ListTest {

    public static void main(String[] args) {
        //并发下ArrayList是不安全的
        List<String> list = new CopyOnWriteArrayList<>();

        /**
         * 解决方案:
         * 1.List<String> list = new Vector<>();Vector加了synchronized保证同步
         * 2.Collections.synchronizedList(new ArrayList<>());集合的同步方法
         * 3.List<String> list = new CopyOnWriteArrayList<>();线程安全的
         */

        /**
         * CopyOnWrite 写入时复制 cow 计算机程序设计领域的一种优化策略,
         * 多个线程调用list,读取是固定的,写入避免直接覆盖原数组,造成数据问题
         * 读写分离的思想
         */
        for (int i = 1; i <= 10; i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(list);
            },String.valueOf(i)).start();
        }
    }
}

Set不安全

image-20230816162305909

package com.landu.unsafe;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;

//java.util.ConcurrentModificationException 并发修改异常
@SuppressWarnings("all")
public class SetTest {
    public static void main(String[] args) {
 //       Set<String> set = new HashSet<>();
        Set<String> set = new CopyOnWriteArraySet<>();

        /**
         * 解决方案:
         * 1.Set<String> set = Collections.synchronizedSet(new HashSet<>());集合安全的
         * 2.Set<String> set = new CopyOnWriteArraySet<>();线程安全的
         */
        for (int i = 1; i <= 30; i++) {
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(set);
            },String.valueOf(i)).start();
        }
    }
}

Hashset的底层是什么?

public HashSet() {
    map = new HashMap<>();
}

//add方法 set本质就是map,key值是无法重复的且无序,value为一个默认值PRESENT
public boolean add(E e) {
   	return map.put(e, PRESENT)==null;
}

HashMap不安全

image-20230816164034389

package com.landu.unsafe;


import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

//java.util.ConcurrentModificationException 并发修改异常
@SuppressWarnings("all")
public class MapTest {

    public static void main(String[] args) {
        //map是这样用的吗? 不是,工作中不用hashmap
        //默认等价于什么?new HashMap<>(16,0.75);
//        Map<String, String> map = new HashMap<>();
        Map<String, String> map = new ConcurrentHashMap<>();
        /**
         * 解决方案:
         * 1.Map<String, String> map = Collections.synchronizedMap(new HashMap<>());集合安全的
         * 2.Map<String, String> map = new ConcurrentHashMap<>();线程安全的
         */
        for (int i = 1; i <= 10; i++) {
            new Thread(()->{
                map.put(Thread.currentThread().getName()
                        ,UUID.randomUUID().toString().substring(0,5));
                System.out.println(map);
            },String.valueOf(i)).start();
        }
    }
}

7.Callable

image-20230817134043517

  • 可以有返回值

  • 可以抛出异常

  • Runnable的方法为run(),而Callable方法为call()

代码测试

image-20230817134540128

image-20230817135123694

image-20230817135309805

package com.landu.callable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

@SuppressWarnings("all")
public class CallableTest {

    public static void main(String[] args) {
        //传统方式功能有限
//        new Thread(new MyThread()).start();

        /**
         * new Thread(new Runnable()).start();
         * new Thread(new FutureTask<String>(Callable)).start();
         */
        MyThread myThread = new MyThread();
        FutureTask<String> task = new FutureTask<String>(myThread); //适配类
        new Thread(task,"A").start();
        new Thread(task,"B").start(); //结果会被缓存,效率高

        //获取返回值
        String s = null;
        try {
            s = task.get(); //这个get方法可能会产生阻塞,把他放到最后
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        //或者使用异步通信来处理
        System.out.println(s);
    }
}

class MyThread implements Callable<String> {

    @Override
    public String call() {
        System.out.println("call()");
        //耗时的操作
        return "123";
    }
}

  1. 有缓存
  2. 结果可能需要等待,会阻塞

8.常用的辅助类

8.1 CountDownLatch

image-20230817141210777

package com.landu.add;


import java.util.concurrent.CountDownLatch;

//减法计数器
@SuppressWarnings("all")
public class CountDownLatchDemo {

    public static void main(String[] args) throws InterruptedException {
        //总数为6,在执行一些必要的任务,再使用!
        CountDownLatch count = new CountDownLatch(6);

        for (int i = 0; i < 6; i++) {

            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "go out");
                count.countDown(); //数量减一
            },String.valueOf(i)).start();
        }

        count.await(); //等待计数器归0,然后向下执行

        System.out.println("close door");
    }
}

原理:

count.countDown(); //数量减一

count.await(); //等待计数器归0,然后向下执行

每次有线程调用countDown()数量-1,假设计数器变为0,count.await();方法就会被唤醒,继续执行

8.2 CyclicBarrier

package com.landu.add;


import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

//加法计数器
@SuppressWarnings("all")
public class CyclicBarrierDemo {

    public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
        CyclicBarrier barrier = new CyclicBarrier(12,()->{
            System.out.println("数量到10关门");
        });

        for (int i = 0; i < 10; i++) {

            //lamdba表达式不能直接操作i
            final int temp = i;
            new Thread(()->{
                System.out.println(Thread.currentThread().getName() + "open door" + temp);
                try {
                    barrier.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } catch (BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            },String.valueOf(i)).start();
        }
    }
}

8.3 Semaphore

Semaphore:信号量

image-20230817143935840

package com.landu.add;


import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

//信号量
@SuppressWarnings("all")
public class SemaphoreDemo {

    public static void main(String[] args) {

        //信号量,假设有3个停车位,6个车
        Semaphore semaphore = new Semaphore(3);

        for (int i = 1; i <= 6; i++) {
            new Thread(()->{
                try {
                    //得到车位
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "抢到车位");
                    //等待几秒
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(Thread.currentThread().getName() + "离开车位");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }finally {
                    //释放资源
                    semaphore.release();
                }
            },String.valueOf(i)).start();
        }
    }
}

原理:

semaphore.acquire();获得,假设如果已经满了,等待,等待被释放!

semaphore.release();释放,会将当前的信号量+1,然后唤醒等待的线程!

作用:多个共享资源互斥的使用!并发限流,控制最大线程数!

9.读写锁

image-20230817145507649

package com.landu.readandwrite;


import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * ReadWriteLock,读写锁
 * 独占锁(写锁)
 * 共享锁(读锁)
 */

@SuppressWarnings("all")
public class ReadWriteLockDemo {

    public static void main(String[] args) {

        MyCacheLock myCache = new MyCacheLock();

        //写入
        for (int i = 1; i <= 6; i++) {
            final int temp = i;
            new Thread(()->{
                myCache.put(temp+"",temp+"");
            },String.valueOf(i)).start();
        }

        //读取
        for (int i = 1; i <= 6; i++) {
            final int temp = i;
            new Thread(()->{
                myCache.get(temp+"");
            },String.valueOf(i)).start();
        }
    }
}

/**
 * 自定义缓存
 */

@SuppressWarnings("all")
class MyCacheLock {

    private volatile Map<String, Object> map = new HashMap<>();
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    //存储就是写入的过程
    public void put(String key,Object value) {
        readWriteLock.writeLock().lock();
        ReadWriteLock lock = new ReentrantReadWriteLock();
        try {
            System.out.println(Thread.currentThread().getName() + "写入" + key);
            map.put(key,value);
            System.out.println(Thread.currentThread().getName() + "写入ok");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    //获取就是读取的过程
    public void get(String key) {
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "读取" + key);
            Object o = map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取ok");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            readWriteLock.readLock().unlock();
        }
    }
}
@SuppressWarnings("all")
class MyCache {

    private volatile Map<String, Object> map = new HashMap<>();

    //存储就是写入的过程
    public void put(String key,Object value) {
        System.out.println(Thread.currentThread().getName() + "写入" + key);
        map.put(key,value);
        System.out.println(Thread.currentThread().getName() + "写入ok");
    }

    //获取就是读取的过程
    public void get(String key) {
        System.out.println(Thread.currentThread().getName() + "读取" + key);
        Object o = map.get(key);
        System.out.println(Thread.currentThread().getName() + "读取ok");
    }
}

10.阻塞队列

image-20230817165609366

什么情况下使用阻塞队列:多线程并发处理,线程池!

四组API

方式 抛出异常 有返回值 阻塞等待 超时等待
添加 add offer() put() offer(,,,)
移除 remove poll() take() poll(,,)
判断队列首 element peek() - -
package com.landu.bq;


import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 1.抛出异常
 */
@SuppressWarnings("all")
public class BqTest1 {
    public static void main(String[] args) {
        BlockingQueue<String> queue1 = new ArrayBlockingQueue<>(3);

        System.out.println(queue1.add("a"));
        System.out.println(queue1.add("b"));
        System.out.println(queue1.add("c"));

        /**
         * 容量为3,添加第四个,抛出异常 IllegalStateException Queue full,
         * 队列已满,无法再添加
         */
//        System.out.println(queue1.add("d"));

        System.out.println(queue1.remove());
        System.out.println(queue1.remove());
        System.out.println(queue1.remove());

        /**
         * 只有三个元素,移除第四个抛出异常,NoSuchElementException
         * 没有元素异常
         */
//        System.out.println(queue1.remove());
    }
}

package com.landu.bq;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 2.有返回值
 */
@SuppressWarnings("all")
public class BqTest2 {
    public static void main(String[] args) {
        BlockingQueue<String> queue2 = new ArrayBlockingQueue<>(3);

        System.out.println(queue2.offer("a"));
        System.out.println(queue2.offer("b"));
        System.out.println(queue2.offer("c"));

        /**
         * 容量为3,添加第四个会返回false
         */
//        System.out.println(queue2.offer("d"));

        System.out.println(queue2.poll());
        System.out.println(queue2.poll());
        System.out.println(queue2.poll());

        /**
         * 只有三个元素,移除第四个会返回null
         *
         */
//        System.out.println(queue2.poll());
    }
}
package com.landu.bq;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 3.一直等待
 */
@SuppressWarnings("all")
public class BqTest3 {

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> queue3 = new ArrayBlockingQueue<String>(3);


        queue3.put("a");
        queue3.put("a");
        queue3.put("a");

        /**
         * 容量为3,put第四个就阻塞等待
         */
//        queue3.put("a");

        System.out.println(queue3.take());
        System.out.println(queue3.take());
        System.out.println(queue3.take());

        /**
         * 容量为3,take第四个就阻塞等待第四个进入后再弹出
         */
//        System.out.println(queue3.take());
    }
}
package com.landu.bq;

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

/**
 * 4.超时等待,过时不候
 */
@SuppressWarnings("all")
public class BqTest4 {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> queue4 = new ArrayBlockingQueue<String>(3);

        System.out.println(queue4.offer("a"));
        System.out.println(queue4.offer("b"));
        System.out.println(queue4.offer("c"));

        /**
         * 容量为3,添加第四个就会等待2秒,
         * 2秒后如果添加不进去,结束等待,给出fasle
         */
//        System.out.println(queue4.offer("d", 2, TimeUnit.SECONDS));

        System.out.println(queue4.poll());
        System.out.println(queue4.poll());
        System.out.println(queue4.poll());

        /**
         * 等待两秒弹出,如果没有,返回null
         */
//        System.out.println(queue4.poll(2,TimeUnit.SECONDS));
    }
}

SynchronousQueue 同步队列

顾名思义:可以在队列中存储一个元素,这个元素被取出来才能存下一个,否则就等待

存put,取take

package com.landu.bq;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 * 同步队列
 * put一次,如果不取出,就会一直等待线程不终止
 */
@SuppressWarnings("all")
public class SynchronousQueueDemo {

    public static void main(String[] args) {
        BlockingQueue queue = new SynchronousQueue();

        new Thread(()->{
            try {
                System.out.println(Thread.currentThread().getName() + "put 1");
                queue.put("1");
                System.out.println(Thread.currentThread().getName() + "put 2");
                queue.put("2");
                System.out.println(Thread.currentThread().getName() + "put 3");
                queue.put("3");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },"T1").start();
        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
                System.out.println(Thread.currentThread().getName()+ "=>" + queue.take());
                TimeUnit.SECONDS.sleep(2);
                System.out.println(Thread.currentThread().getName()+ "=>" + queue.take());
                TimeUnit.SECONDS.sleep(2);
                System.out.println(Thread.currentThread().getName()+ "=>" + queue.take());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },"T2").start();
    }
}

11.线程池(重点)

池化技术

程序的运行的本质:占用系统的资源!优化资源的使用!=>池化技术

线程池,连接池,内存池,对象池 =>线程池的创建和销毁十分的浪费系统资源

池化技术:事先预备一些资源以提供程序的使用,在程序使用完毕之后,再把资源还给池子

线程池的好处:

  • 降低了对资源的消耗
  • 提高了相应的速度
  • 创建的线程池,能够统一管理

线程复用,可以控制最大并发数,管理线程

线程池:三大方法

package com.landu.pool;

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

/**
 *Executors 线程工具类 3大方法
 */
@SuppressWarnings("all")
public class Demo01 {
    public static void main(String[] args) {
        //创建单个线程
//        ExecutorService threadPool = Executors.newSingleThreadExecutor();

        //创建固定的线程池大小
//        ExecutorService threadPool = Executors.newFixedThreadPool(5);

        //创建可伸缩的线程池,遇强则强,遇弱则弱
        ExecutorService threadPool = Executors.newCachedThreadPool();

        try {
            //初始化10个任务
            /**
             * 分配的资源已经远远大于系统的最大资源数,抛出异常,OutOfMemoryError内存溢出异常
             */
            for (int i = 1; i <= 10; i++) {
                //使用线程池来创建线程
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName() + " ok");
                });
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //程序结束后,关闭线程池
            threadPool.shutdown();
        }
    }
}

七大参数

源码分析:

public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>()));
}

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}

// 本质:ThreadPoolExecutor()
public ThreadPoolExecutor(int corePoolSize, // 核心线程大小
                          int maximumPoolSize, // 最大核心线程大小
                          long keepAliveTime, // 超时了,没有人调用,就会释放
                          TimeUnit unit, // 超时单位
                          BlockingQueue<Runnable> workQueue, // 阻塞队列
                          ThreadFactory threadFactory, // 线程工厂,创建线程的,一般不用动
                          RejectedExecutionHandler handler // 拒绝策略) {
    if (corePoolSize < 0 ||
        maximumPoolSize <= 0 ||
        maximumPoolSize < corePoolSize ||
        keepAliveTime < 0)
        throw new IllegalArgumentException();
    if (workQueue == null || threadFactory == null || handler == null)
        throw new NullPointerException();
    this.acc = System.getSecurityManager() == null ?
            null :
            AccessController.getContext();
    this.corePoolSize = corePoolSize;
    this.maximumPoolSize = maximumPoolSize;
    this.workQueue = workQueue;
    this.keepAliveTime = unit.toNanos(keepAliveTime);
    this.threadFactory = threadFactory;
    this.handler = handler;
}

手动创建线程池

package com.landu.pool;

import java.util.concurrent.*;

/**
 *ThreadPoolExecutor 自定义线程池
 * ThreadPoolExecutor.AbortPolicy() 出现java.util.concurrent.RejectedExecutionException 拒绝执行异常
 * ThreadPoolExecutor.CallerRunsPolicy() main线程来处理,哪来的回哪去
 * ThreadPoolExecutor.DiscardPolicy() 队列满了,丢掉任务,不会抛出异常
 * ThreadPoolExecutor.DiscardOldestPolicy() 队列满了,尝试去和最早的竞争,也不会抛出异常
 */
@SuppressWarnings("all")
public class Demo01 {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        ExecutorService threadPool = new ThreadPoolExecutor(
                2,
                5,
                2,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy()
        );


        try {
            /**
             * 最大并发数为8个,是最大核心数加阻塞队列数
             */
            for (int i = 1; i <= 9; i++) {
                //使用线程池来创建线程
                threadPool.execute(()->{
                    System.out.println(Thread.currentThread().getName() + " ok");
                });
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //程序结束后,关闭线程池
            threadPool.shutdown();
        }
    }
}

四种拒绝策略

image-20230818150652924

/**
 *ThreadPoolExecutor 自定义线程池
 * ThreadPoolExecutor.AbortPolicy() 出现java.util.concurrent.RejectedExecutionException 拒绝执行异常
 * ThreadPoolExecutor.CallerRunsPolicy() main线程来处理,哪来的回哪去
 * ThreadPoolExecutor.DiscardPolicy() 队列满了,丢掉任务,不会抛出异常
 * ThreadPoolExecutor.DiscardOldestPolicy() 队列满了,尝试去和最早的竞争,也不会抛出异常
 */

小结和拓展

/**
 * 最大线程如何定义:
 * 1.cpu密集型:cpu有几核,最大线程数就设置为几
 * 2.IO密集型:判断你程序中十分消耗io资源的任务,大于任务的数量的两倍就行
 */

//获取运行时的核数
System.out.println(Runtime.getRuntime().availableProcessors());

12.四大函数式接口

了解:lambda表达式,链式编程,函数式接口,Stream流式计算

函数式接口:只有一个方法的接口

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

image-20230824210433804

Function:函数式接口

image-20230824211002568

package com.landu.function;


import java.util.function.Function;

/**
 * Function 函数型接口
 * 只要是函数式接口,可以用lambda表达式简化
 */
@SuppressWarnings("all")
public class Demo01 {
    public static void main(String[] args) {
        Function<String,String> function = new Function<String,String>() {
            @Override
            public String apply(String o) {
                return o;
            }
        };

        Function<String,String> function1 = (str)->{return str;};

        String asd = function1.apply("asd");
        System.out.println(asd);
    }
}

Predicate:断定式接口

package com.landu.function;

import java.util.function.Predicate;

/**
 * Predicate 断定式接口,有一个参数,返回值只能是布尔值
 *
 */
@SuppressWarnings("all")
public class Demo02 {
    public static void main(String[] args) {
        Predicate<String> predicate = new Predicate<String>() {
            @Override
            public boolean test(String s) {
                if (!s.equals("hello")) return false;
                else return true;
            }
        };

        Predicate<String> predicate1 = str->{return str.isEmpty();};
        System.out.println(predicate1.test("asd"));
    }
}

Consumer 消费型接口

image-20230904192749324

package com.landu.function;

import java.util.function.Consumer;

/**
 * Consumer 消费型接口:只有输入,没有返回值
 */
@SuppressWarnings("all")
public class Demo03 {
    public static void main(String[] args) {
//        Consumer<String> consumer = new Consumer<String>() {
//            @Override
//            public void accept(String str) {
//                System.out.println(str);
//            }
//        };

        Consumer<String> consumer = (str)->{
            System.out.println(str);
        };
        consumer.accept("asd");
    }
}

Supplier 供给型接口

image-20230904193314550

package com.landu.function;

import java.util.function.Supplier;

/**
 * Supplier 供给型接口:没有输入值,获取返回值
 */
public class Demo04 {
    public static void main(String[] args) {
//        Supplier<String> supplier = new Supplier<String>() {
//            @Override
//            public String get() {
//                return "hello";
//            }
//        };

        Supplier<String> supplier = ()->{return "hello";};
        String s = supplier.get();
        System.out.println(s);
    }
}

13.Stream流式计算

什么是Stream流式计算

大数据:存储+计算

集合包括mysql本质就是存储东西的

计算都应该交给流来操作

image-20230904195209853

package com.landu.stream;


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

/**
 * 题目要求:
 * 1.id必须为偶数
 * 2.年龄必须大于25岁
 * 3.用户名转为大写字母
 * 4.用户名字符倒着排序
 * 5.只输出一个用户
 */
public class Test {
    public static void main(String[] args) {
        User u1 = new User(1,"a",21);
        User u2 = new User(2,"b",22);
        User u3 = new User(3,"c",23);
        User u4 = new User(4,"d",24);
        User u5 = new User(5,"e",25);
        User u6 = new User(6,"f",26);

        //集合用来存储
        List<User> list = Arrays.asList(u1, u2, u3, u4, u5,u6);

        //流式用来计算
        list.stream()
                .filter(u->{return u.getId() % 2 == 0;})
                .filter(u->{return u.getAge() > 23;})
                .map(u->{return u.getName().toUpperCase();})
                .sorted((o1, o2) -> o2.compareTo(o1))
                .limit(1)
                .forEach(System.out::println);
    }
}

14.ForkJoin

分支合并

image-20230904204731233

ForkJoin 工作窃取

维护的是双端队列,在B线程优先执行完自己的任务,A线程还没有执行完,B线程会窃取A线程的任务

ForkJoin 计算

package com.landu.forkJoin;

import java.util.concurrent.RecursiveTask;

/**
 * 求和计算
 */
@SuppressWarnings("all")
public class ForkJoinDemo extends RecursiveTask<Long> {

    private Long start;
    private Long end;

    //临界值
    private Long temp = 10000L;

    public ForkJoinDemo(Long start,Long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        if ((end - start) < temp) {
            Long sum = 0L;
            for (Long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        }else {
            //分支合并计算 forkjoin
            Long mid = (start + end) / 2;

            //把task1的任务压入线程里面
            ForkJoinDemo task1 = new ForkJoinDemo(start, mid);
            task1.fork();

            //把task2的任务压入线程里面
            ForkJoinDemo task2 = new ForkJoinDemo(mid+1, end);
            task2.fork();

            return task1.join() + task2.join();
        }
    }
}
package com.landu.forkJoin;

import org.omg.PortableServer.POA;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

@SuppressWarnings("all")
public class Test {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //test1(); // 9175

        //test2(); // 4261

        test3(); // 203
    }

    public static void test1() {
        Long sum = 0L;
        long start = System.currentTimeMillis();

        for (Long i = 1L;i <= 10_0000_0000;i++) {
            sum +=i;
        }

        long end = System.currentTimeMillis();

        System.out.println("sum=" + sum + " 时间:" + (end - start));
    }

    public static void test2() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinDemo forkJoinDemo = new ForkJoinDemo(0L, 10_0000_0000l);
        ForkJoinTask<Long> submit = pool.submit(forkJoinDemo);
        Long sum = submit.get();
        long end = System.currentTimeMillis();
        System.out.println("sum=" + sum + " 时间:" + (end - start));
    }

    //Stream流计算
    public static void test3() {
        long start = System.currentTimeMillis();
        long sum = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0, Long::sum);
        long end = System.currentTimeMillis();

        System.out.println("sum=" + sum + " 时间:" + (end - start));
    }
}

15.异步回调

Future 设计的初衷:对将来的某个事件进行建模

image-20230905162154555

package com.landu.Future;

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

/**
 * 异步回调: CompletableFuture
 * 1.异步执行
 * 2.成功回调
 * 3.失败回调
 */
public class Demo01 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //没有返回值的异步回调 runAsync
//        CompletableFuture<Void> future = CompletableFuture.runAsync(()->{
//            try {
//                TimeUnit.SECONDS.sleep(2);
//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            }
//            System.out.println(Thread.currentThread().getName() + "future=>Void");
//        });
//
//        System.out.println("hello");
//        future.get();

        //有返回值的异步回调 supplyAsync
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(()->{
            System.out.println(Thread.currentThread().getName() + "supplyAsync=>Integer");
            int i = 10/0;
            return 1024;
        });

        System.out.println(future.whenComplete((t, u) -> {
            System.out.println("t=>" + t); //获取正常的结果
            System.out.println("u=>" + u); // 错误信息:java.lang.ArithmeticException: / by zero
        }).exceptionally((e) -> {
            e.getMessage(); //获取错误信息
            return 233; //返回错误结果
        }).get());

        /**
         * success code 200
         * error code 404 500
         */
    }
}

16.JMM

请你谈谈对Volatile的理解

Volatile:是Java虚拟机提供的轻量级的同步机制

  1. 保证可见性
  2. 不保证原子性
  3. 禁止指令重排

什么是JMM

JMM:Java内存模型,一种约定

关于一些JMM的同步约定

  1. 线程解锁前,必须把共享变量立刻刷回主存
  2. 线程加锁前,必须读取主存中的最新值到工作内存中
  3. 加锁和解锁是同一把锁

线程:工作内存主内存

8种操作:

image-20230908190136579

image-20230908190322933

package com.landu.cvolatile;

import java.util.concurrent.TimeUnit;

@SuppressWarnings("all")
public class JMMDemo {

    private  static int num = 0;

    //启动一个main线程和子线程
    public static void main(String[] args) {

        new Thread(()->{
            while (num == 0) {

            }
        }).start();

        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        num = 1;
        System.out.println(1);
    }
}

17.Volatile

1.保证可见性

package com.landu.cvolatile;

import java.util.concurrent.TimeUnit;

@SuppressWarnings("all")
public class JMMDemo {


    //添加volatile关键字保证了可见性
    private volatile   static int num = 0;

    //启动一个main线程和子线程
    public static void main(String[] args) {

        new Thread(()->{
            while (num == 0) {

            }
        }).start();

        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        num = 1;
        System.out.println(1);
    }
}

2.不保证原子性

原子性:不可分割

线程A在执行任务的时候,不能被打扰的,也不能被分割。要么同时成功,要么同时失败

package com.landu.cvolatile;


//不保证原子性
@SuppressWarnings("all")
public class VDemo02 {

    //volatile不保证原子性操作
    private volatile static int num = 0;

    public static void add() {
        num++;
    }
    public static void main(String[] args) {

        for (int i = 1; i <= 20 ; i++) {
            new Thread(()->{
                for (int j = 0; j < 1000; j++) {
                    add();
                }
            }).start();
        }

        //默认两个线程为main线程和gc线程
        while (Thread.activeCount() > 2) {
            Thread.yield();
        }

        System.out.println(Thread.currentThread().getName() + " " + num);
    }
}

如果不加locksynchronized,怎样保证原子性?

image-20230908193248198

image-20230908193441663

package com.landu.cvolatile;


import java.util.concurrent.atomic.AtomicInteger;

//不保证原子性
@SuppressWarnings("all")
public class VDemo02 {

    //volatile不保证原子性操作
    //AtomicInteger 原子类来保证原子性操作
    private volatile static AtomicInteger num = new AtomicInteger(0);

    public static void add() {
        // num++;
        num.getAndIncrement();
    }
    public static void main(String[] args) {

        for (int i = 1; i <= 20 ; i++) {
            new Thread(()->{
                for (int j = 0; j < 1000; j++) {
                    add();
                }
            }).start();
        }

        //默认两个线程为main线程和gc线程
        while (Thread.activeCount() > 2) {
            Thread.yield();
        }

        System.out.println(Thread.currentThread().getName() + " " + num);
    }
}

3.禁止指令重排

什么是指令重排:你写的程序,计算机并不是按照你写的那样去执行的

源代码->编译器优化重排->指令并行也可能重排->内存系统也会重排->执行代码

处理器在进行指令重排的时候,考虑:数据之间的依赖性!

volatile可以避免指令重排:

内存屏障,cpu指令作用:

1.保证特定的操作执行顺序

2.可以保证某些变量的内存可见性(利用这些特性volatile实现了可见性)

19.深入理解CAS

Unsafe类

image-20230911100409602

image-20230911100759865

package com.landu.cas;

import java.util.concurrent.atomic.AtomicInteger;

//CAS compareAndSet 比较并交换
//如果期望值达到了,就更新,否则就不更新
@SuppressWarnings("all")
public class casDemo {

    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(2020);

        System.out.println(atomicInteger.compareAndSet(2020, 2021));

        System.out.println(atomicInteger);

        System.out.println(atomicInteger.compareAndSet(2020, 2023));

        System.out.println(atomicInteger);

        atomicInteger.getAndIncrement();
    }
}

CAS缺点:

  1. 循环会耗时间
  2. 一次性只能保证一个共享变量的原子性
  3. ABA问题

ABA问题

image-20230911143553487

package com.landu.cas;

import java.util.concurrent.atomic.AtomicInteger;

//CAS compareAndSet 比较并交换
//如果期望值达到了,就更新,否则就不更新
@SuppressWarnings("all")
public class casDemo {

    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(2020);

        //正常的线程期望值为2020
        System.out.println(atomicInteger.compareAndSet(2020, 2021));
        System.out.println(atomicInteger);

        //插入一个捣乱的线程进行修改
        System.out.println(atomicInteger.compareAndSet(2021, 2020));
        System.out.println(atomicInteger);

        //期望的线程
        System.out.println(atomicInteger.compareAndSet(2020, 2023));
        System.out.println(atomicInteger);

    }
}

20.原子引用

带版本号的原子引用

package com.landu.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

//CAS compareAndSet 比较并交换
//如果期望值达到了,就更新,否则就不更新
@SuppressWarnings("all")
public class casDemo {

    public static void main(String[] args) {
        AtomicStampedReference<String> reference = new AtomicStampedReference<String>("2020",1);


        new Thread(()->{
            int stamp = reference.getStamp();
            System.out.println( "a1=>"+ stamp);

            //a线程休眠1秒
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            //进行修改
            System.out.println(reference.compareAndSet("2020", "2023",
                    reference.getStamp(), reference.getStamp()+1));
            System.out.println("a2=>"+ reference.getStamp());

            //再改回来
            System.out.println(reference.compareAndSet("2023", "2020"
                    , reference.getStamp(), reference.getStamp()+ 1));
            System.out.println("a3=>"+ reference.getStamp());

        },"a").start();


        new Thread(()->{
            int stamp = reference.getStamp();
            System.out.println("b1=>" + stamp);

            //b线程休眠3秒
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            System.out.println(reference.compareAndSet("2020", "6666",
                    stamp, stamp + 1));
            System.out.println("b2=>" + reference.getStamp());
        },"b").start();
    }
}

21.各种锁的理解

1.公平锁和非公平锁

公平锁:顾名思义,非常公平,必须先来后到!

非公平锁:顾名思义,非常不公平,可以插队!

public ReentrantLock() {
    sync = new NonfairSync();
}
public ReentrantLock(boolean fair) {
    sync = fair ? new FairSync() : new NonfairSync();
}

2.可重入锁

拿到外面的锁,相当于也拿到了里面的锁

package com.landu.lock;


//Synchronized
@SuppressWarnings("all")
public class Demo01 {

    public static void main(String[] args) {
        Phone phone = new Phone();

        new Thread(()->{
            phone.message();
        },"A").start();
        new Thread(()->{
            phone.message();
        },"B").start();
    }
}

class Phone {

    public synchronized static void message() {
        System.out.println(Thread.currentThread().getName() + " message");
        call();
    }

    public synchronized static void call() {
        System.out.println(Thread.currentThread().getName() + " call");
    }
}
package com.landu.lock;

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

//Lock
@SuppressWarnings("all")
public class Demo02 {

    public static void main(String[] args) {
        Phone2 phone2 = new Phone2();

        new Thread(()->{
            phone2.message();
        },"A").start();
        new Thread(()->{
            phone2.message();
        },"B").start();
    }
}

class Phone2 {

    Lock lock = new ReentrantLock();

    public  void message() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " message");
            call();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public void call() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " call");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}

3.自旋锁

package com.landu.lock;

import java.util.concurrent.atomic.AtomicReference;

//自旋锁
@SuppressWarnings("all")
public class SpinlockDemo {

    AtomicReference<Thread> atomicReference = new AtomicReference();

    //加锁
    public void myLock() {
        Thread thread = Thread.currentThread();

        System.out.println(Thread.currentThread().getName() + "==> myLock");

        //自旋锁
        while (!atomicReference.compareAndSet(null,thread)) {

        }
    }
    //解锁
    public void myUnLock() {
        Thread thread = Thread.currentThread();

        System.out.println(Thread.currentThread().getName() + "==> myUnLock");

        atomicReference.compareAndSet(thread,null);
    }

}
package com.landu.lock;

import java.util.concurrent.TimeUnit;

public class TestSpinlock {

    public static void main(String[] args) throws InterruptedException {
        SpinlockDemo spinlockDemo = new SpinlockDemo();

        new Thread(()->{
            spinlockDemo.myLock();
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                spinlockDemo.myUnLock();
            }

        },"T1").start();

        TimeUnit.SECONDS.sleep(1);
        new Thread(()->{
            spinlockDemo.myLock();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                spinlockDemo.myUnLock();
            }
        },"T2").start();
    }
}

4.死锁

package com.landu.lock;


import java.util.concurrent.TimeUnit;

//死锁
@SuppressWarnings("all")
public class DeadLockDemo {
    public static void main(String[] args) {
        String lockA = "lockA";
        String lockB = "lockB";

        new Thread(new MyThread(lockA,lockB),"T1").start();
        new Thread(new MyThread(lockB,lockA),"T1").start();
    }
}


class MyThread implements Runnable{

    private String lockA;
    private String lockB;

    public MyThread(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {
        synchronized (lockA) {
            System.out.println(Thread.currentThread().getName() + "A==>B");

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            synchronized (lockB) {
                System.out.println(Thread.currentThread().getName() + "B==>A");
            }
        }
    }
}

解决死锁的思路:

  1. 使用命令 jps -l 查看进程

image-20230911163556714

2.使用命令 jstack 进程号 进行查看信息

image-20230911163838983

image-20230911163940903

标签:JUC,Thread,编程,System,并发,println,new,public,out
From: https://www.cnblogs.com/mbkss/p/17693921.html

相关文章

  • 详解Java多线程编程中线程的启动、中断或终止操作
    ​在Java中start和tun方法可用被用来启动线程,而用interrupt方法来中断或终止线程,以下我们就来详解Java多线程编程中线程的启动、中断或终止操作 线程启动: 1.start()和run()的区别说明start():它的作用是启动一个新线程,新线程会执行相应的run()方法。start()不能被......
  • 技术文档 | 免下载、0配置、多任务并发,在Docker Image中使用OpenSCA
    想跳过下载步骤快速使用OpenSCA检测代码风险?想实现多个项目并发扫描?在DockerImage中使用OpenSCA即可轻松实现。一起来looklook目的方便用户使用最新版本的 OpenSCA-cli保证环境的一致性,消除不同操作系统对结果的影响可以方便在本地维护不同版本的 OpenSCA-cli方便在特定情况下......
  • Java后端开发中的并发编程
    引言在Java后端开发中,处理并发是一个常见但具有挑战性的任务。本博客将深入探讨Java中的并发编程,包括多线程、线程安全性和常见的并发问题。多线程基础多线程是Java后端开发中的重要概念。它允许我们同时执行多个任务,提高了系统的性能和响应能力。下面是一个简单的多线程示例:pu......
  • 深入了解Python协程与异步编程
    Python是一门强大的编程语言,提供了多种方式来处理并发和异步编程。在本博客中,我们将深入探讨Python中的协程(coroutines)和异步编程的重要性。什么是协程?协程是一种轻量级的线程,允许在一个线程中执行多个任务,而无需线程切换的开销。在Python中,协程通过asyncio库来实现。importasy......
  • 3天上手Ascend C编程丨通过Ascend C编程范式实现一个算子实例
    本文分享自华为云社区《3天上手AscendC编程|Day2通过AscendC编程范式实现一个算子实例》,作者:昇腾CANN。一、AscendC编程范式AscendC编程范式把算子内部的处理程序,分成多个流水任务(stage),以张量(Tensor)为数据载体,以队列(Queue)进行任务之间的通信与同步,以内存管......
  • Java并发编程的艺术-PDF下载-firebook-书火网
    Java并发编程的艺术-PDF下载-firebook-书火网资源链接:https://pan.baidu.com/s/19vG6Dd3YBr69i6D2NHeCaQ提取码:wv4f第1章介绍Java并发编程的挑战,会向读者说明可能会遇到哪些问题,以及如何解决。第2章Java并发编程的底层实现原理,从CPU和JVM2个层面剖析。第3章详细深入介绍了Ja......
  • 多进程编程之守护进程Daemonize
    1、守护进程守护进程(daemon)是一类在后台运行的特殊进程,用于执行特定的系统任务。很多守护进程在系统引导的时候启动,并且一直运行直到系统关闭。另一些只在需要的时候才启动,完成任务后就自动结束。所有的守护进程都没有控制终端,其终端名设置为问号。2、编程规则1)首先......
  • Win32编程之资源文件(三)
    一、菜单资源的使用1.菜单的分类窗口的顶层菜单弹出式菜单系统菜单HMENU类型表示菜单,ID表示菜单项2、菜单资源的使用 (1).注册窗口类时设置菜单 (2).创建窗口传参设置菜单 (3).在主窗口WM_CREATE消息中利用SetMenu函数设置菜单 加载菜单资源HMENULoadMenu( ......
  • unix/linux系统编程第一、二章知识归纳
    1.引言1.1Unix&Linux简介及历史版本Unix和Linux是一系列强大的操作系统,具有丰富的历史和版本。Unix的初始版本由肯·汤普森(KenThompson)和丹尼斯·里奇(DennisRitchie)于20世纪70年代早期开发。它是一种通用操作系统,经典书目包括1988年的《TheCProgrammingLang......
  • Java是一种面向对象的编程语言
    Java是一种面向对象的编程语言,泰兰德幻化广泛应用于各种平台上。它的特点是可移植性强,安全性高,且具有很强的扩展性。Java语言采用了“一次编写,到处运行”的原则,这意味着可以在不同的操作系统和设备上运行相同的Java程序,无需对代码进行修改。Java语言有着丰富的类库和API,可以满足......