Bootstrap

线程并发篇03

死锁避免方法

  • 死锁产生的四个必要条件
    1.互斥条件:一个资源每次只能被一个进程使用
    2.请求与保持条件:一个进程因请求资源而阻塞时,对已获取的资源保持不放
    3.不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺
    4.循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系
  • 破坏其中的任意一个或多个条件就可以避免死锁发生

synchronized 与 Lock 对比

  • Lock是显式锁(手动开启和关闭锁),synchronized是隐式锁,出了作用域自动释放
  • Lock只有代码锁,synchronized有代码块和方法锁
  • 使用Lock锁,JVM将花费较少的时间来调度线程,性能更好,具有更好的扩展性(提供更多的子类)
  • 优先使用顺序:Lock > 同步代码块(已经进入了方法体,分配了相应资源)> 同步方法(在方法体之外)

生产者消费者问题

  • 管程法
package com.tu.gaoji;
//测试:生产者消费者模型--->利用缓冲区解决:管程法
//生产者,消费者,产品,缓冲区
public class TestPC {
    public static void main(String[] args) {
        SynContainer container = new SynContainer();

        new Productor(container).start();
        new Consumer(container).start();
    }
}
class Productor extends Thread{
    SynContainer container;
    public Productor(SynContainer container){
        this.container = container;
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                container.push(new Chicken(i));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("生产了第"+i+"只鸡");
        }
    }
}
class Consumer extends Thread{
    SynContainer container;
    public Consumer(SynContainer container){
        this.container = container;
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                Thread.sleep(1000);
                System.out.println("消费了"+container.pop().id+"只鸡");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
class Chicken{
    int id;//产品编号
    public Chicken(int id){
        this.id = id;
    }
}
//缓冲区
class SynContainer{
    Chicken[] chickens = new Chicken[10];
    int count = 0;
    public synchronized void push(Chicken chicken) throws InterruptedException {
        if (count == chickens.length){
            //通知消费者等待
            this.wait();

        }
        //如果没有满,我们就需要丢入产品
        chickens[count++] = chicken;
        //通知消费者可以消费了
        this.notifyAll();

    }
    //消费者消费产品
    public synchronized Chicken pop() throws InterruptedException {
        if (count == 0){
            //等待生产者生产,消费者等待
            this.wait();
        }
        //如果可以消费
        Chicken chicken = chickens[--count];
        this.notifyAll();
        return chicken;
    }

}
  • 信号灯法
package com.tu.gaoji;

public class TestPC2 {
    public static void main(String[] args) {
        TV tv = new TV();
        new Player(tv).start();
        new Watcher(tv).start();
    }
}
class Player extends Thread{
    TV tv;
    public Player(TV tv){
        this.tv = tv;
    }
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if(i % 2 == 0){
                try {
                    this.tv.play("喜羊羊与灰太狼");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }else {
                try {
                    this.tv.play("怎敌她千娇百媚");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
class Watcher extends Thread{
    TV tv;
    public Watcher(TV tv){
        this.tv = tv;
    }
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            try {
                this.tv.watch();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
class TV{
    String voice;
    boolean flag = true;
    public synchronized void play(String voice) throws InterruptedException {
        if (!flag){
            this.wait();
        }
        System.out.println("演员表演了:"+voice);
        //通知观众观看
        this.notifyAll();
        this.voice = voice;
        this.flag = !flag;
    }
    public synchronized void watch() throws InterruptedException {
        if (flag){
            this.wait();
        }
        System.out.println("观看了:"+voice);
        //通知演员表演
        this.notifyAll();
        this.flag = !this.flag;
    }
}

线程池

  • 背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大
  • 思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中,可以避免频繁创建销毁、实现重复利用。类似生活中的公共交通工具
  • 好处:
    1.提高响应速度(减少了创建新线程的时间)
    2.降低资源消耗(重复利用线程池中的线程,不需要每次都创建)
    3.便于线程管理:
    corePoolSize:核心池的大小
    maximumPoolSize:最大线程数
    keepAliveTime:线程没有任务时最多保持多长时间后会终止
  • ExecutorService:真正的线程池接口。常见子类ThreadPoolExecutor
  • void execute(Runnable command):执行任务/命令,没有返回值,一般用来执行Runnable
  • Future submit(Callable task):执行任务,有返回值,一般执行Callable
  • void shutdown():关闭连接池
  • Executors:工具类、线程池的工厂类,用于创建并返回不同类型的线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//测试线程池
public class TestPool {
    public static void main(String[] args) {
        //1.创建服务,创建线程池
        //newFixedThreadPool  参数为:线程池大小
        ExecutorService service = Executors.newFixedThreadPool(10);
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        //2.关闭连接
        service.shutdown();
    }
}
class MyThread implements Runnable{

    @Override
    public void run() {
            System.out.println(Thread.currentThread().getName());
    }
}

回顾总结

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
//回顾总结线程的创建
public class ThreadNew {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //继承Thread
        new MyThread1().start();
        //Runnable
        MyThread2 myThread2 = new MyThread2();
        new Thread(myThread2).start();
        //Callable
        FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyThread3());
        new Thread(futureTask).start();
        Integer i = futureTask.get();
        System.out.println(i);
    }
}
//1.继承Thread类
class MyThread1 extends Thread{
    @Override
    public void run() {
        System.out.println("MyThread1");
    }
}
//2.实现Runnable接口
class MyThread2 implements Runnable{

    @Override
    public void run() {
        System.out.println("MyThread2");
    }
}
//3.实现Callable接口
class MyThread3 implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        System.out.println("MyThread3");
        return 1;
    }
}
;