JUC并发编程(上)

借用网络上大神的知识体系图
在这里插入图片描述

什么是JUC?

JUC是java.util.concurrent的简写。在jdk官方手册中可以看到juc相关的jar包有三个:java.util.concurrent、
java.util.concurrent.atomic、java.util.concurrent.locks。
用中文概括一下,JUC的意思就是java并发编程工具包

在这里插入图片描述

进程和线程

进程和线程

进程:进程就是系统中一个正在运行的应用程序,程序一旦运行就是进程
进程是系统资源分配的独立实体,每个进程都拥有独立的地址空间

线程:线程是进程的一条执行路径,是CPU独立运行和独立调度的基本单元,
java中默认有两个线程:main线程和GC线程
java中提供了三种方法操作线程,Tread、Runnable、Callable
java中的线程开启是由java完成的吗?
当然不是的,java中调用的start方法是由native修饰,代表该方法为本地方法,底层是由c++提供和操作,java无法开启运行。

在这里插入图片描述

并发和并行

并发:一个处理器处理多个任务(一个CPU,多条线程执行)
并行:多个处理器处理多个任务(多个CPU,多条线程执行)
获取本地cpu的核数

public class Test1 {
    public static void main(String[] args) {
      // 获取cpu的核数 
     // CPU 密集型,IO密集型 
        System.out.println(Runtime.getRuntime().availableProcessors());
     // 如果电脑是8核,则结果输出8
     } 
}

并发编程的本质:充分利用CPU的资源

线程的状态:

NEW(新建)—>RUNNABLE(就绪)—>RUNNING(运行)—>DEAD(死亡)
                                                                ↓                                     ↑
                                                               —>BLOCKED(阻塞)----

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的区别

1、出处不同:wait来自Object类,sleep来自Thread类
2、锁的释放:wait会释放锁,sleep不会释放锁,并抱着锁睡觉
3、作用范围:wait只能在同步代码块中使用(被synchronized修饰的方法或者代码块),sleep可以在代码的任何地方使用

Synchronized锁

1、修饰方法

	Synchronized修饰普通方法时,锁是对象锁(this)。
	new几个对象几把锁。

        当该类中有多个普通方法被Synchronized修饰(同步),那么这些方法的锁都是这个类的一个对象this。多个线程访问这些方法时,如果这些线程调用方法时使用的是同一个该类的对象,虽然他们访问不同方法,但是他们使用同一个对象来调用,那么这些方法的锁就是一样的,就是这个对象,那么会造成阻塞。如果多个线程通过不同的对象来调用方法(一般都是通过同一个对象访问),那么他们的锁就是不一样的,不会造成阻塞。

public class TestSynchronized {
    public static void main(String[] args) {
        test test = new test();
        
        new Thread(() -> {
            test.test2();
        }).start();

        new Thread(() -> {
            test.test1();
        }).start();

    }

}

class test {
    public void test1() {
        System.out.println(Thread.currentThread().getName() + "我进来了");
    }

    public synchronized void test2() {
        System.out.println(Thread.currentThread().getName() + "我进来了");
            System.out.println(Thread.currentThread().getName() + "获取到锁");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        System.out.println(Thread.currentThread().getName() + "我出来了");
    }
}

2、修饰代码块(只需要锁住共享功能即可)

修饰代码块时,作用范围为整个代码块,锁的对象可以自定义,最好设置为需要改变的方法的对象。多个线程调用同一个同步代码块的方法时,其他线程阻塞在同步代码块外,其他线程可以获取或者调用没锁住的资源

public class TestSynchronized {
    public static void main(String[] args) {
        test test = new test();

        new Thread(() -> {
            test.test2();
        }).start();

        new Thread(() -> {
            test.test2();
        }).start();
    }

}
class test {
    public void test2() {
        System.out.println(Thread.currentThread().getName() + "我进来了");
        synchronized (this) {
            System.out.println(Thread.currentThread().getName() + "获取到锁");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + "我出来了");
    }
}

3、修饰静态方法

synchronized修饰静态方法
锁是类锁(.class)。这个范围就比对象锁大。这里就算是不同对象,但是只要是该类的对象,就使用的是同一把锁。多个线程调用该类的同步的静态方法时,都会阻塞。

Lock锁(重点)

在concurrent.locks下
包括三个常用的锁,ReentrantLock,ReentrantReadWriteLock.ReadLock,ReentrantReadWriteLock.WriteLock
在这里插入图片描述

公平锁和非公平锁

公平锁:不允许插队,按照先后顺序执行
非公平锁:允许插队。随机执行
ReentrantLock默认为非公平锁,但是可以通过传入参数定义为公平锁
在这里插入图片描述

ReentrantLock的使用

public class TestJUC03 {
    public static void main(String[] args) {
        SaleTicket1 saleTicket1 = new SaleTicket1();
        new Thread(()->{ for (int i = 0; i < 100; i++) saleTicket1.saleTicket1(); },"牛儿").start();

        new Thread(()->{ for (int i = 0; i < 100; i++) saleTicket1.saleTicket1(); },"老君").start();

        new Thread(()->{ for (int i = 0; i < 100; i++) saleTicket1.saleTicket1(); },"炼丹童子").start();
    }
}

class SaleTicket1 {
    private int ticketNum = 90;
    //创建ReentrantLock对象
    ReentrantLock lock = new ReentrantLock();

    public void saleTicket1() {
        try {
            //加锁
            lock.lock();
            if (ticketNum > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出了" + 1 + "张票," + "剩余" + --ticketNum + "张");
            }
        } finally {
            //释放锁
            lock.unlock();
        }
    }

}

synchronized和lock的区别是

 1、synchronized是java关键字,lock是一个java类
 2、synchronized方法执行完后自动释放锁,lock需要手动加锁和释放锁,不释放会造成死锁
 3、synchronized无法获取到锁的状态,lock可以获取到锁
 4、synchronized加锁后,线程一获得锁,线程二只能等待,lock可能等待,可能不等待
 5、synchronized非公平锁,lock默认是非公平锁,但可设置为公平锁
 6、synchronized适合锁住少量同步代码,lock适合锁住大量同步代码

生产者和消费者问题

synchronized版本的生产者和消费者问题

public class TestSynchronized01 {

    public static void main(String[] args) {
        Data data = new Data();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();

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

class Data {
    //记录产品数量
    int productNum = 0;

    //在假设只生产一个产品
    //生产
    public synchronized void increment() throws InterruptedException {
        //假如有产品,则等待
        while(productNum != 0) {
            this.wait();
        }
        productNum++;
        //没产品就生产
        System.out.println(Thread.currentThread().getName() + "=====>" + productNum);
        this.notifyAll();
    }

    //消费
    public synchronized void decrement() throws InterruptedException {
        //假如没有产品就等待
        while(productNum == 0) {
            this.wait();
        }
        //有产品就消费
        productNum--;
        System.out.println(Thread.currentThread().getName() + "======>" + productNum);
        this.notifyAll();
    }
}

上面代码中A、B线程存在虚假唤醒。

什么是虚假唤醒?

上述例子中,每次生产者只生产一个产品,消费者也只能消费一个产品;当产品被生产或消费时,生产者或消费者会执行
notifyAll()方法唤醒所有等待线程,但只有一个线程能够生产或者消费产品,如果生产者或消费者使用if()条件语句去执
行等待,那么其他没有生产或者消费的产品的线程就不会继续进入等待状态,会继续执行if()条件以后的逻辑,如果将if
换为while后如果线程没有生产或消费产品时会继续进入等待,直到满足条件后才会被唤醒

我理解的虚假唤醒就是,线程被叫醒,但是没事情干,就会继续执行往下的逻辑,而不是重新进入等待状态。

官方文档 java.lang包下 找到Object ,然后找到wait()方法:在这里插入图片描述

JUC版的生产者和消费者问题

public class TestReentrantLock01 {

    public static void main(String[] args) {
        Data3 data = new Data3();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.increment();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.decrement();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.increment();
            }
        }, "C").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.decrement();
            }
        }, "D").start();
    }
}

class Data3 {
    int i = 0;
    //创建lock锁
    ReentrantLock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    //在假设只生产一个产品
    //生产
    public void increment() {
        lock.lock();
        try {
            //假如有产品,则等待
            while (i != 0) {
                //等待
                condition.await();
            }
            i++;
            //没产品就生产
            System.out.println(Thread.currentThread().getName() + "生产=====>" + i);
            //通知其他线程
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    //消费
    public void decrement() {
        lock.lock();
        try {
            //假如没有产品就等待
            while (i == 0) {
                condition.await();
            }
            //有产品就消费
            System.out.println(Thread.currentThread().getName() + "消费=====>" + i--);
            //唤醒其他全部线程
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

ReentrantLock是使用Condition对象让线程进行等待或者唤醒

在这里插入图片描述
在这里插入图片描述

Condition 精准的通知和唤醒线程

ABC四个线程是随机抢占资源,如果让三个线程按顺序执行?
这里就需要用到Condition的精准通知和唤醒功能

首先创建三个Condition对象,
再定义一个标识,每次有一个线程执行时,
会获取标识并将标识,
执行完内容后更改为下一个线程能够获取到的标识。
并通过Condition对象唤醒对应标识的线程
public class TestReentrantLock02 {

    public static void main(String[] args) {
        Data4 data = new Data4();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.A();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.B();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.C();
            }
        }, "C").start();
    }
}

class Data4 {
    int num = 1;
    //创建lock锁
    ReentrantLock lock = new ReentrantLock();
    //创建Condition对象
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    //方法A如果num==1进入
    public void A() {
        lock.lock();
        try {
            //num不等于1,等线程等待
            while (num != 1) {
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName()+"=>AAAAA");
            //将num修改为2
            num = 2;
            //唤醒方法B
            condition2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void B() {
        lock.lock();
        try {
            while (num != 2) {
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName()+"=>BBBBB");
            num = 3;
            condition3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

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

}

八锁现象

一、两个同步方法,一个对象调用

public class test1 {
    public static void main(String[] args) throws InterruptedException {
        Animal animal = new Animal();
        new Thread(()->{
            animal.tortoise();
        }).start();
        TimeUnit.SECONDS.sleep(1);
        new Thread(()->{
            animal.rabbit();
        }).start();
    }
}
class Animal{

    public synchronized void tortoise(){
        System.out.println("乌龟先跑");
    }
    public synchronized  void rabbit(){
        System.out.println("兔子先跑");
    }
}

乌龟先跑
原因:synchronized 锁的是方法的调用者,也就是对象锁。两个方法持有的是同一把锁,因此谁先拿到锁谁先执行。

二、两个同步方法,一个对象调用

public class test4 {
    public static void main(String[] args) {
        Animal3 animal1=new Animal3();

        new Thread(()->{
            animal1.wuGui();
        }).start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(()->{
            animal1.tuZi();
        }).start();
    }
}

class Animal3{

    public synchronized void wuGui(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("乌龟先跑");
    }
    public synchronized void tuZi(){
        System.out.println("兔子先跑");
    }
}

乌龟先跑
原因:synchronized 锁的是方法的调用者,也就是对象锁。两个方法持有的是同一把锁,因此谁先拿到锁谁先执行。

三、 两个同步方法,两个对象调用

public class test2 {
    public static void main(String[] args) {
        Animal1 animal1 = new Animal1();
        Animal1 animal2 = new Animal1();
        new Thread(() -> {
            animal1.wuGui();
        }).start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            animal2.tuZi();
        }).start();
    }
}

class Animal1 {
    public synchronized void wuGui() {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("乌龟先跑");
    }

    public synchronized void tuZi() {
        System.out.println("兔子先跑");
    }
}

兔子先跑
原因:synchronized 锁的是方法的调用者,也就是对象锁。两个对象分别调用两个方法持有的是两把把锁,兔子不需要等待。

四、一个同步方法,一个普通方法,一个对象调用

public class test3 {
    public static void main(String[] args) {
        Animal2 animal1 = new Animal2();

        new Thread(() -> {
            animal1.wuGui();
        }).start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            animal1.Laohu();
        }).start();
    }


}

class Animal2 {
    public synchronized void wuGui() {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("乌龟先跑");
    }

    public void Laohu() {
        System.out.println("老虎先跑");
    }
}

老虎先跑
原因:普通方法没有锁,不需要竞争锁。

五、两个静态同步方法,一个对象调用

public class test5 {
    public static void main(String[] args) {
        Animal5 animal1=new Animal5();

        new Thread(()->{
            animal1.wuGui();
        }).start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(()->{
            animal1.tuZi();
        }).start();
    }
}

class Animal5{
    public synchronized void wuGui(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("乌龟先跑");
    }

    public synchronized void tuZi(){
        System.out.println("兔子先跑");
    }
}

乌龟先跑
原因:static方法类一加载就执行,synchronized 锁的是Class对象即类锁,所以两个方法持有一把锁,谁先得到谁先执行。

六、两个静态同步方法,两个对象调用

public class test6 {
    public static void main(String[] args) {
        Animal6 animal1=new Animal6();
        Animal6 animal2=new Animal6();

        new Thread(()->{
            animal1.wuGui();
        }).start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(()->{
            animal2.tuZi();
        }).start();
    }
}

class Animal6{

    public static synchronized void wuGui(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("乌龟先跑");
    }
    public static synchronized void tuZi(){
        System.out.println("兔子先跑");
    }
}

乌龟先跑
原因:static方法类一加载就执行,synchronized 锁的是Class对象即类锁,所以两个方法持有一把锁,谁先得到谁先执行。(多线程访问同一个类的静态同步方法(不管是同一个还是多个),只要是用相同对象new出来的,都是同一把锁(类锁),都得遵循先到先得的原则)

七、 一个静态同步方法,一个普通同步方法

public class test7 {
    public static void main(String[] args) {
        Animal7 animal1=new Animal7();

        new Thread(()->{
            animal1.wuGui();
        }).start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(()->{
            animal1.tuZi();
        }).start();
    }
}

class Animal7{

    public static synchronized void wuGui(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("乌龟先跑");
    }
    public synchronized void tuZi(){
        System.out.println("兔子先跑");
    }
}

兔子先跑
原因:静态同步方法和普通同步方法分别是类锁和对象锁,相当于两把锁,普通同步方法不要等待。

八、一个静态同步方法,一个普通同步方法,两个对象调用

public static void main(String[] args) {
        Animal8 animal1=new Animal8();
        Animal8 animal2=new Animal8();

        new Thread(()->{
            animal1.wuGui();
        }).start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(()->{
            animal2.tuZi();
        }).start();
    }
}

class Animal8{

    public static synchronized void wuGui(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("乌龟先跑");
    }
    public synchronized void tuZi(){
        System.out.println("兔子先跑");
    }
}

兔子先跑
原因:静态同步方法和普通同步方法分别是类锁和对象锁,相当于两把锁,普通同步方法不要等待。

集合类不安全

List不安全

多线程操作Arraylist集合时,会导致多个线程操作同一个位置而报错:java.util.ConcurrentModificationException

线程不安全解决办法有三种:使用vector、Collections.synchronized(new ArrayList())、CopyOnWriteArrayList

  • CopyOnWrite写入时复制,简称COW 计算机程序设计领域的一种优化策略,
  • 多个线程调用的时候,list,读取的时候是固定的,写入就会发生覆盖(set方法),
  • 在写入的时候避免发生覆盖,造成数据问题!
  • CopyOnWriteArrayList 比 Vector 不同点在哪里?(底层没有用synchronized,而是用的lock)
public class TestList {
    public static void main(String[] args) {
        //线程不安全的集合
        List<String> list = new ArrayList<>();
        //线程安全的集合
        //List<String> list = new Vector<>();
        //List<String> list = Collections.synchronizedList(new ArrayList<>());
        //CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 5));
                System.out.println(list);
            }).start();
        }
    }
}

Set不安全

set的底层是HashMap,HashMap的key就是set存入的值,value就是一个不变的Object对象,但是HashMap的key值不允许重复,所以多个线程操作set时会报错:java.util.ConcurrentModificationException

集合不安全的解决办法:
1、Collections.synchronizedSet(new HashSet<>()
2、CopyOnWriteArraySet<>()
在这里插入图片描述

public class TestSet {
    public static void main(String[] args) {

        //线程不安全的set
        HashSet<Object> set = new HashSet<>();
        //线程安全的set
        //Set<Object> set = Collections.synchronizedSet(new HashSet<>());
        //CopyOnWriteArraySet<Object> set = new CopyOnWriteArraySet<>();
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(set);
            }).start();
        }
    }
}

Map不安全

因为HashMap的key值不能重复,所以多线程操作同一个key时就会报错:java.util.ConcurrentModificationException
解决办法:
1、new ConcurrentHashMap<>
2、Collections.synchronizedMap(new HashMap<>())

public class TestHashMap {
    public static void main(String[] args) {
        // 不安全的map
        Map<String, String> map = new HashMap<>(16, 0.75F);
        //安全的map
        //Map<String, String> map = new ConcurrentHashMap<>();
        //Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0,5));
                System.out.println(map);
            }).start();
        }
    }
}

Callable

在这里插入图片描述
Runnable和Callable的区别
1、Runnable不能跑出异常,Callable可以
2、Runnable没有返回值,Callable有返回值
3、Runnable必须实现run()方法,Callable实现的是call()方法

public class TestCallable {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyCall myCall = new MyCall();
        FutureTask futureTask = new FutureTask(myCall);// 适配类
        new Thread(futureTask,"A").start();
        new Thread(futureTask,"B").start();// call()方法结果会被缓存,提高效率,因此只打印1个call
        // 这个get 方法可能会产生阻塞!把他放到最后
        Integer integer = (Integer) futureTask.get();
        System.out.println(integer);

    }
}

class MyCall implements Callable {
    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName()+":call");// A,B两个线程会打印几个call?(1个)
    return 1024;
    }
}

注意:FutureTask其实就是一个适配类,把callable接口转换成可以被Thead对象识别的Runable接口。
这种方法有利也有弊,相比之前的Runable接口,他的返回结果是有缓存的,所以效率会想对应较快,而且也能够抛出异常,但是它的获取返回结果的get方法就可能会出现阻塞。

常用的辅助类

CountDownLatch

在这里插入图片描述
CountDownLatch能够使一个线程在等待另外一些线程完成各自工作之后,再继续执行。使用一个计数器进行实现。计数器初始值为线程的数量。当每一个线程完成自己任务后,计数器的值就会减一。当计数器的值为0时,表示所有的线程都已经完成一些任务,然后在CountDownLatch上等待的线程就可以恢复执行接下来的任务
不足之处
CountDownLatch是一次性的,计算器的值只能在构造方法中初始化一次,之后没有任何机制再次对其设置值,当CountDownLatch使用完毕后,它不能再次被使用。

public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
// 总数是6,必须要执行任务的时候使用
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 0; i < 6; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"=>Go Out");
countDownLatch.countDown();// 数量-1
}).start();
}
//等待所有线程都执行完后,全部等待,再执行下面的逻辑
countDownLatch.await();// 等待计数器归零,然后再往下执行
System.out.println(“关门”);
}
}

CyclicBarrier

在这里插入图片描述
CyclicBarrier,让一组线程到达一个同步点后再一起继续运行,在其中任意一个线程未达到同步点,其他到达的线程均会被阻塞。

public class CyclicBarrierDemo {

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
            System.out.println("召唤神龙");
        });
        for (int i = 0; i < 7; i++) {
            final int temp = i;
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "收集了第" + temp + "龙珠");
                try {
                    //await()方法会做两件事,1、线程等待,2线程计数-1
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}

CyclicBarrier和CountDownLatch区别
CountdownLatch阻塞主线程,等所有子线程完结了再继续下去。Syslicbarrier阻塞一组线程,直至某个状态之后再全部同时执行,并且所有线程都被释放后,还能通过reset来重用。
使用CycliBarrier赛马

package com.lcj.juc;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

public class HorseRace implements Runnable {

    private static final int FINISH_LINE = 75;
    private static List<Horse> horses = new ArrayList<Horse>();
    private static ExecutorService exc = Executors.newCachedThreadPool();

    @Override
    public void run() {
        //打印赛道边界
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < FINISH_LINE; i++) {
            stringBuilder.append("=");
        }
        System.out.println(stringBuilder);
        //打印赛马轨迹
        for (Horse horse : horses) {
            System.out.println(horse.tracks());
            if (horse.getStrides() >= FINISH_LINE) {
                System.out.println(horse + "won!");
                exc.shutdownNow();
                return;
            }
        }
        /*for (Horse horse : horses) {
            if (horse.getStrides() >= FINISH_LINE) {
                System.out.println(horse + "won!");
                exc.shutdownNow();
                return;
            }
        }*/
        //休息指定之间到下一轮
        try {
            TimeUnit.MILLISECONDS.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(7, new HorseRace());
        for (int i = 0; i < 7; i++) {
            Horse horse = new Horse(cyclicBarrier);
            horses.add(horse);
            exc.execute(horse);
        }
    }
}

class Horse implements Runnable {
    private static int counter = 0;
    //马走的步数
    private int strides = 0;
    //马的编号
    private final int id = counter++;

    private static Random random = new Random(47);
    //栅栏
    private static CyclicBarrier cyclicBarrier;

    public Horse() {
    }

    public Horse(CyclicBarrier cyclicBarrier) {
        this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
        try {
            //线程没有被打断就需要等到
            while (!Thread.interrupted()) {
                synchronized (this) {
                    strides += random.nextInt(3);
                }
                cyclicBarrier.await();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }

    //打印轨道
    public String tracks() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < strides; i++) {
            sb.append("*");
        }
        //凭借马的id
        sb.append(id);
        return sb.toString();
    }

    public int getStrides() {
        return strides;
    }

    public String toString() {
        return "Horse " + id + " ";
    }
}

Semaphore

在这里插入图片描述

public class SemaphoreDemo {
    public static void main(String[] args) {
        //相当于有三个车位,六部车来抢,只有车位空出来,其他的才能抢到车位
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; 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) {
                    e.printStackTrace();
                } finally {
                    //释放资源
                    semaphore.release();
                }
            }).start();

        }
    }
}

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

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

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

读写锁

ReadWriteLock
在这里插入图片描述

/**
 * 读写锁,写的时候会一个个来,读的时候可以多条线程同时进行
 * 当有读线程和写线程时,会先保证写线程先执行
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCacheLock myCacheLock = new MyCacheLock();
        for (int i = 0; i < 100; i++) {
            final int temp=i;
            new Thread(()->{
                myCacheLock.put(temp+"",temp+"");
            },String.valueOf(i)).start();
        }

        for (int i = 0; i < 100; i++) {
            final int temp=i;
            new Thread(()->{
                myCacheLock.get(temp+"");
            },String.valueOf(i)).start();
        }
    }
}
class MyCacheLock {

    Map<String, Object> map = new HashMap<>();
    ReentrantReadWriteLock rrwl = new ReentrantReadWriteLock();

    public void put(String key, Object value) {

        rrwl.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "写入");
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写入完成");
        } finally {
            rrwl.writeLock().unlock();
        }
    }
    public void get(String key) {
        rrwl.readLock().lock();
        try{
            System.out.println(Thread.currentThread().getName() + "读取");
            map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取成功");
        }finally {
            rrwl.readLock().unlock();
        }
    }
}

阻塞队列

BlockingQueue

在这里插入图片描述
在这里插入图片描述

方式抛出异常有返回值,不抛出异常阻塞 等待超时等待
添加addoffer()put()offer(,)
移除removepoll()take()poll(,)
检测队首元素elementpeek()--
public class TestBlockingQueue {
    public static void main(String[] args) throws InterruptedException {
//        test1();
//        test2();
//        test3();
        test4();
    }

    /**
     * 测试add、element、remove
     */
    public static void test1() {
        ArrayBlockingQueue abq1 = new ArrayBlockingQueue<>(3);
        //如果添加的字段大于队列的长度报错,Exception in thread "main" java.lang.IllegalStateException: Queue full
        abq1.add("a");
        abq1.add("b");
        abq1.add("c");
        //abq1.add("d");
        System.out.println(abq1.element());
        //如果移除队列中没有的元素报错,Exception in thread "main" java.util.NoSuchElementException
        Object a1 = abq1.remove();
        Object a2 = abq1.remove();
        Object a3 = abq1.remove();
        Object a4 = abq1.remove();
    }
    // 有返回值,不抛出异常
    public static void test2(){
        // 队列的大小为3
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
        // offer返回boolean值
        boolean flag1 = blockingQueue.offer("a");
        boolean flag2 = blockingQueue.offer("b");
        boolean flag3 = blockingQueue.offer("c");
        boolean flag4 = blockingQueue.offer("d");// offer添加元素超过队列的长度会返回false
        System.out.println(flag4);
        System.out.println(blockingQueue.peek());// 获得队首元素
        System.out.println("=========");
        // poll()返回本次移除的元素
        Object poll1 = blockingQueue.poll();
        Object poll2 = blockingQueue.poll();
        Object poll3 = blockingQueue.poll();
        Object poll4 = blockingQueue.poll();// 队列中没有元素仍继续移除元素会打印出null
        System.out.println(poll4);
    }

    // 阻塞,一直等待
    public static void test3() throws InterruptedException {
        // 队列的大小为3
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
        // put没有返回值
        blockingQueue.put("a");
        blockingQueue.put("b");
        blockingQueue.put("c");
        //blockingQueue.put("d");// put添加元素超过队列的长度会一直等待
        System.out.println("=========");
        // take()返回本次移除的元素
        Object take1 = blockingQueue.take();
        Object take2 = blockingQueue.take();
        Object take3 = blockingQueue.take();
        Object take4 = blockingQueue.take();// 队列中没有元素仍继续移除元素会一直等待
    }
    // 阻塞,超时等待
    public static void test4() throws InterruptedException {
        // 队列的大小为3
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
        // offer返回boolean值
        boolean flag1 = blockingQueue.offer("a");
        boolean flag2 = blockingQueue.offer("b");
        boolean flag3 = blockingQueue.offer("c");
        // offer添加元素超过队列的长度会返回false;并且等待指定时间后推出,向下执行
        boolean flag4 = blockingQueue.offer("d", 2, TimeUnit.SECONDS);
        System.out.println("=========");
        // poll()返回本次移除的元素
        Object poll1 = blockingQueue.poll();
        Object poll2 = blockingQueue.poll();
        Object poll3 = blockingQueue.poll();
        // 队列中没有元素仍继续移除元素会打印出null,等待指定之间后退出。
        Object poll4 = blockingQueue.poll(2,TimeUnit.SECONDS);
    }

}

SynchronousQueue

没有容量,进去一个元素,必须等待取出来之后,才能再往里面放一个元素!

public class SynchronousQueueDemo {

    public static void main(String[] args) {
        BlockingQueue<String> squeue =
                new SynchronousQueue<>(); // 同步队列
        //放入数据
        new Thread(()->{
            try {
                System.out.println("放入put1");
                squeue.put("1");
                System.out.println("放入put2");
                squeue.put("2");
                System.out.println("放入put3");
                squeue.put("3");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"A").start();

        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName()+"===>"+squeue.take());
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName()+"===>"+squeue.take());
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName()+"===>"+squeue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"B").start();
    }
}

线程池

线程池:4大方法、7大参数、4种拒绝策略
池化技术

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

线程池、连接池、内存池、对象池。。。创建、销毁。十分浪费资源

池化技术:事先准备好一些资源,有人要用,就来我这里拿,用完之后还给我。

线程池的好处:

  1. 降低资源的消耗
  2. 提高响应的速度
  3. 方便管理
    线程复用、可以控制最大并发数、管理线程

阿里巴巴开发规范:线程池不允许使用Executors去创建,而是通过ThreadPoolExecutor的方式去创建,这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。.
说明Executors创建线程池的弊端:
1)FixedThreadPool和SingleThreadPool:
允许请求队列长度为Integer.MAX_VALUE,可能会堆积大量的请求,从而导致OOM.
2)CacheThreadPool和ScheduleTreadPool:
允许创建线程的数量为Integer.MAX_VALUE,可能会创建大量的线程,从而导致OOM.

线程池:4大方法

1、SingleThreadPool 单一线程池
2、FixedThreadPool 核心线程池
3、CachedThreadPool 缓存线程池
4、ScheduledThreadPool 定时线程池

public static void main(String[] args) {
//        ExecutorService threadPool = Executors.newSingleThreadExecutor(); //创建单个线程的线程池,线程池内只存在一个线程
//        ExecutorService threadPool = Executors.newFixedThreadPool(5); //创建核心线程数量为5的线程池
//        ExecutorService threadPool = Executors.newCachedThreadPool(); //创建缓存线程池,不存在核心线程
        ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(3); //创建核心线程数量为3的定时线程池
        try {
            for (int i = 0; i < 50; i++) {
                final int index=i;
                //使用线程池创建线程
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "创建成功");
                    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                    System.out.println("运行时间: " + sdf.format(new Date()) + " " + index);
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
            }
        } finally {
            //所有线程都执行完毕后,关闭线程池
            threadPool.shutdown();
        }
    }
}

线程池:7大参数

在这里插入图片描述

手动创建线程池

public class Demo1 {
    public static void main(String[] args) {
        //获取CPU核数
        System.out.println(Runtime.getRuntime().availableProcessors());
        //创建线程池
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                2,//核心线程池大小
                5, //根据上面的方法判断
                3, //超时3秒没有人调用就会释放
                TimeUnit.SECONDS, //超时单位 秒
                new LinkedBlockingQueue<Runnable>(3), //阻塞队列(候客区最多3人)
                Executors.defaultThreadFactory(),//默认线程工厂
                new ThreadPoolExecutor.CallerRunsPolicy());
       try {
           for (int i = 1; i <= 9; i++) {
                //最大承载(最大线程数)5+(队列大小)3
               //超出最大承载就会跑出异常
               threadPool.execute(() -> {
                   System.out.println(Thread.currentThread().getName() + " ok");
               });
           }
       }finally {
           //关闭线程池
           threadPool.shutdown();
       }
    }
}

线程池:4种拒绝策略

在这里插入图片描述
四种拒绝策略

  • new ThreadPoolExecutor.AbortPolicy()
    队列满了,直接抛出RejectedExcutionException异常
  • new ThreadPoolExecutor.CallerRunsPolicy()
    队列满了,会将任务回退给任务提交者线程执行
  • new ThreadPoolExecutor.DiscardPolicy()
    队列满了,放弃任务,也不会抛出任何异常
  • new ThreadPoolExecutor.DiscardOldestPolicy()
    队列满了,尝试和最早的任务竞争,成功执行,失败删除任务,也不会跑出异常

最大的线程如何去设置!

了解:IO密集型、CPU密集型**》调优

  • IO密集型,判断系统中有多少耗IO的线程,一般设置为2倍
  • CPU密集型,几核就是几,可以保持CPU的效率最高!
public class Demo1 {
    public static void main(String[] args) {
        //获取CPU核数
        System.out.println(Runtime.getRuntime().availableProcessors());
        //最大线程数的如何定义
        //CPU密集型  几核就写几,可以保持CPU效率最高
        //8核 最大线程数设置为8
        //IO密集型   根据程序中十分消耗资源的io个数来填写,填写的数量必须大于程序中耗费资源的io数量,一般设置io的两倍
        //15个耗费资源的io   最大线程数设置为30
        //创建线程池
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                2,//核心线程池大小
                5, //根据上面的方法判断
                3, //超时3秒没有人调用就会释放
                TimeUnit.SECONDS, //超时单位 秒
                new LinkedBlockingQueue<Runnable>(3), //阻塞队列(候客区最多3人)
                Executors.defaultThreadFactory(),//默认线程工厂
                new ThreadPoolExecutor.CallerRunsPolicy());
       try {
           for (int i = 1; i <= 9; i++) {
                //最大承载(最大线程数)5+(队列大小)3
               //超出最大承载就会跑出异常
               threadPool.execute(() -> {
                   System.out.println(Thread.currentThread().getName() + " ok");
               });
           }
       }finally {
           //关闭线程池
           threadPool.shutdown();
       }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值