目录
7.2 方式二: ScheduledExecutorService
1、线程概述
1.1 什么是线程?
1.2 什么是多线程?
1、多线程是指从软硬件上实现多条执行路径的技术。
2、多线程用在哪里,有什么好处?
例如铁路12306购票系统。
例如过年回家抢票,不可能只有你一个人在买票,那每个人进来的时候都要有一个执行路径,那这个之后就需要用到多线程。
2、多线程的创建
2.1 继承Thread类
实现过程:
代码实现:
package com.jie.multithreading;
/**
 * @description:多线程创建方式
 * @author: jie
 * @time: 2022/3/20 9:30
 */
public class ThreadDemo01 {
    public static void main(String[] args) {
        //3、new一个新线程对象
        Thread t = new MyThread();
        //4、调用start方法启动线程
        t.start();
        for (int i = 0; i < 5; i++) {
            System.out.println("主线程执行输出"+i);
        }
    }
}
/**
 * @description:1、定义一个线程类继承Thread
 * @author: jie
 * @time: 2022/3/20 9:32
 */
class MyThread extends Thread {
    /**
     * @description:2、重写run方法,里面定义线程以后要干啥
     * @author: jie
     * @time: 2022/3/20 12:26
     */
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("子线程执行输出" + i);
        }
    }
} 
执行结果:

优缺点:
问题:
1、为什么不直接调用了run方法,而是调用start启动线程。
如果直接调用run方法,执行结果如下

2、把主线程任务放在子线程之前了。
执行结果如下:
小结:
2.2 实现Runnable接口
实现过程:
代码实现:
package com.jie.multithreading;
/**
 * @description:多线程创建方式2
 * @author: jie
 * @time: 2022/3/20 12:50
 */
public class ThreadDemo02 {
    public static void main(String[] args) {
        //3、创建一个任务对象
        Runnable target = new MyRunnable();
        //4、把任务对象交给Thread处理
        Thread t = new Thread(target);
        //5、启动线程
        t.start();
        for (int i = 0; i < 5; i++) {
            System.out.println("主线程执行输出:" + i);
        }
    }
}
/**
 * @description:1、定义一个线程类实现Runnable接口
 * @author: jie
 * @time: 2022/3/20 12:53
 */
class MyRunnable implements Runnable {
    /**
     * @description:2、重写run方法,定义线程执行任务的
     * @author: jie
     * @time: 2022/3/20 12:51
     */
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("子线程执行输出:" + i);
        }
    }
} 
执行结果:

优缺点:
小结:
2.3 实现Callable接口
1、前2种线程创建方式都存在一个问题:
2、怎么解决这个问题呢?
实现过程:
代码实现:
package com.jie.multithreading;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
 * @description:创建线程方式3,实现Callable,结合FutureTask完成
 * @author: jie
 * @time: 2022/3/20 14:02
 */
public class ThreadDemo03 {
    public static void main(String[] args) {
        //3、创建Callble任务对象
        Callable<String> call = new Mycallable(100);
        //4、把Callable任务对象,交给FutureTask对象
        //FutureTask对象的作用1 是Runnable的对象(实现了Runnable接口),可以交给Thread了
        //FutureTask对象的作用2 可以在线程执行完毕之后通过调用其Get方法的到线程执行完成的结果
        FutureTask<String> f1 = new FutureTask<>(call);
        //5、交给线程处理
        Thread t1 = new Thread(f1);
        //6、启动线程
        t1.start();
        Callable<String> call1 = new Mycallable(200);
        FutureTask<String> f2= new FutureTask<>(call1);
        Thread t2 = new Thread(f2);
        t2.start();
        try {
            // 如果f1任务没有执行完毕,这里的代码会等待,直到线程1跑完才提取结果
            String s = f1.get();
            System.out.println("第一个结果:"+s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            // 如果f2任务没有执行完毕,这里的代码会等待,直到线程2跑完才提取结果
            String s1 = f2.get();
            System.out.println("第二个结果:"+s1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
/**
 * @description:1、定义一个任务类,实现callable接口, 应该声明线程任务执行完毕后的结果的数据类型
 * @author: jie
 * @time: 2022/3/20 14:04
 */
class Mycallable implements Callable<String> {
    private int n;
    public Mycallable(int n) {
        this.n = n;
    }
    /**
     * @description:2、重写call(任务方法)
     * @author: jie
     * @time: 2022/3/20 14:06
     */
    @Override
    public String call() throws Exception {
        int sum = 0;
        for (int i = 0; i <= n; i++) {
            sum += i;
        }
        return "子线程执行的结果是:" + sum;
    }
} 
执行结果:

FutureTask的API :

优缺点:
2.4 总结
3种方式对比
3、Thread的常用方法
3.1 区分线程
1、给线程设置名称
Thread t = new MyThread();
//线程取名
t.setName("1号"); 
2、得到线程名称
Thread t = new MyThread();
t.getName() 
3、得到当前线程对象,然后再获取名称
Thread m = Thread.currentThread();
System.out.println(m.getName()); 

4、Thread的构造器
 
 代码演示:
 
3.2 休眠方法
 
代码实现:

3.3 总结

4、线程安全
4.1 取钱模型演示
需求:
分析:
代码实现:
账户类:
package com.jie.thread;
import java.math.BigDecimal;
/**
 * @description:账户类
 * @author: jie
 * @time: 2022/3/20 16:29
 */
public class Account {
    private String cardId;
    private BigDecimal money;
    public String getCardId() {
        return cardId;
    }
    public void setCardId(String cardId) {
        this.cardId = cardId;
    }
    public BigDecimal getMoney() {
        return money;
    }
    public void setMoney(BigDecimal money) {
        this.money = money;
    }
    /**
     * @description:取钱
     * @author: jie
     * @time: 2022/3/20 16:47
     */
    public void drawMooney(BigDecimal money){
        //1、先获取是谁来取钱,线程的名字就是人名
        String name = Thread.currentThread().getName();
        //2、判断账户是否够钱
        if(this.money.compareTo(money)!=-1){
            //2.取钱
            System.out.println(name + "来取钱成功,吐出"+money);
            //3.更新余额
            BigDecimal subtract = this.money.subtract(money);
            this.money = subtract;
            System.out.println(name + "取钱后剩余"+this.money);
        }else{
            //余额不足
            System.out.println(name+"来取钱,余额不足");
        }
    }
    public Account(){
    }
    public Account(String cardId, BigDecimal money) {
        this.cardId = cardId;
        this.money = money;
    }
} 
实现类:
package com.jie.thread;
import java.math.BigDecimal;
/**
 * @description:模拟取钱案例
 * @author: jie
 * @time: 2022/3/20 16:28
 */
public class ThreadDemo {
    public static void main(String[] args) {
        //1、定义线程类,创建一个账户对象
        Account account = new Account("jie-1111", BigDecimal.valueOf(100000.0));
        //2、创建两个线程对象,代表小明和小红同时进来了。
        new DrawThread(account,"小明").start();
        new DrawThread(account,"小红").start();
    }
} 
线程类:
package com.jie.thread;
import java.math.BigDecimal;
/**
 * @description:线程类(取钱)
 * @author: jie
 * @time: 2022/3/20 16:39
 */
public class DrawThread extends Thread{
    /**接收处理的账户对象*/
    private Account account;
    public DrawThread(Account account,String name){
        super(name);
        this.account  = account;
    }
    @Override
    public void run() {
      //小明,小红 取钱
        account.drawMooney(BigDecimal.valueOf(100000));
    }
} 
执行结果:
4.2 总结
线程安全问题发生的原因是什么?
5、线程同步
线程同步就是为了解决线程安全问题。
线程同步的核心思想:
5.1 同步代码块
代码实现:

 执行结果:
小结:
1、同步代码块是如何实现线程安全的?
2、 同步代码块的同步锁对象有什么要求?
5.2 同步方法
代码实现:
 
执行结果:

同步方法底层原理:
同步方法其实底层也是有隐式锁对象的,只是锁的范围是整个方法代码。
是同步代码块好还是同步方法好一点?
-  
同步代码块锁的范围更小,同步方法锁的范围更大。
 
但是在实际开发中,同步方法或许会比同步代码块用得更多一点。因为写法方便。
小结:
1、同步方法是如何保证线程安全的?
2、同步方法的同步锁对象的原理?
5.3 Lock锁
 
 Lock的常用API
 代码实现:
执行结果:

6、线程池*
6.1 线程池概述
不使用线程池的问题
谁代表线程池?
6.2 线程池处理Runnable任务
线程类:
package com.jie.threadpool;
public class MyRunnable implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName()+"输出了:"+i);
        }
    }
} 
测试:
package com.jie.threadpool;
import java.lang.annotation.Target;
import java.util.concurrent.*;
/**
 * @description:自定义一个线程池对象,测试其新特性
 * @author: jie
 * @time: 2022/3/20 20:31
 */
public class ThreadPoolDemo01 {
    public static void main(String[] args) {
          //创建线程池对象
        ExecutorService pool = new ThreadPoolExecutor(
                3,
                5,
                6,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(5),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        //2、给任务线程池处理
        MyRunnable runnable = new MyRunnable();
        pool.execute(runnable);
        pool.execute(runnable);
        pool.execute(runnable);
    }
}
 
ThreadPoolExecutor构造器的参数说明
线程池常见面试题:
临时线程什么时候创建啊?
什么时候会开始拒绝任务?
6.3 线程池处理Callable任务
线程类:
package com.jie.threadpool;
import java.util.concurrent.Callable;
/**
 * @description:1、定义一个任务类,实现callable接口, 应该声明线程任务执行完毕后的结果的数据类型
 * @author: jie
 * @time: 2022/3/20 14:04
 */
public class Mycallable implements Callable<String> {
    private int n;
    public Mycallable(int n) {
        this.n = n;
    }
    /**
     * @description:2、重写call(任务方法)
     * @author: jie
     * @time: 2022/3/20 14:06
     */
    @Override
    public String call() throws Exception {
        int sum = 0;
        for (int i = 0; i <= n; i++) {
            sum += i;
        }
        return Thread.currentThread().getName() + "执行1 - " + n + "的和,结果 = " + sum;
    }
} 
测试:
package com.jie.threadpool;
import java.util.concurrent.*;
/**
 * @description:自定义一个线程池对象,测试其新特性
 * @author: jie
 * @time: 2022/3/20 20:31
 */
public class ThreadPoolDemo02 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
          //创建线程池对象
        ExecutorService pool = new ThreadPoolExecutor(
                3,
                5,
                6,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(5),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        //2、给任务线程池处理
        Future<String> f1 = pool.submit(new Mycallable(100));
        Future<String> f2 = pool.submit(new Mycallable(200));
        Future<String> f3 = pool.submit(new Mycallable(300));
        Future<String> f4 = pool.submit(new Mycallable(400));
        System.out.println(f1.get());
        System.out.println(f2.get());
        System.out.println(f3.get());
        System.out.println(f4.get());
    }
} 
测试结果:

6.4 Executors工具类实现线程池
Executors:线程池的工具类通过调用方法返回不同类型的线程池对象。
代码实现:
package com.jie.threadpool;
import com.sun.jndi.ldap.pool.Pool;
import java.util.concurrent.*;
/**
 * @description:使用Executors的工具方法直接得到一个线程池对象
 * @author: jie
 * @time: 2022/3/20 20:31
 */
public class ThreadPoolDemo03 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
          // 1、创建固定线程数据的线程池
        ExecutorService pool = Executors.newFixedThreadPool(3);
        pool.execute(new MyRunnable());
        pool.execute(new MyRunnable());
        pool.execute(new MyRunnable());
    }
} 
Executors使用可能存在的陷阱
 
 
6.5 总结
1、ExecutorService的常用方法
 
 2、新任务拒绝策略 
3、线程池如何处理Runnable任务。
4、线程池如何处理Callable任务,并得到任务执行完后返回的结果。
5、Executors工具类底层是基于什么方式实现的线程池对象?
6、Executors是否适合做大型互联网场景的线程池方案?
7、定时器
概述
实现方式
7.1 实现方式一:Timer
代码实现:
package com.jie.timer;
import java.util.Timer;
import java.util.TimerTask;
/**
 * @description:Timer定时器的使用
 * @author: jie
 * @time: 2022/3/20 22:21
 */
public class TimerDemo01 {
    public static void main(String[] args) {
        //1、创建Timer定时器 定时器本身就是一个单线程
        Timer timer = new Timer();
        //2、调用方法、处理定时任务
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+"执行一次");
            }
        },3000,2000);
    }
} 
Timer定时器的特点和存在的问题
7.2 方式二: ScheduledExecutorService
package com.jie.timer;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
 * @description:ScheduledExecutorService定时器的使用
 * @author: jie
 * @time: 2022/3/20 22:21
 */
public class TimerDemo02 {
    public static void main(String[] args) {
        //1、创建ScheduledExecutorService线程池做定时器
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(3);
        //2、开启定时任务
        pool.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+"执行输出:AAA");
            }
        },0,2, TimeUnit.SECONDS);
    }
} 
ScheduledExecutorService的优点
8、并发、并行
并发的理解
并行的理解
小结:
9、线程生命周期
线程的状态
Java总共定义了6种状态
Java总共定义了6种状态
6种状态都定义在Thread类的内部枚举类中。
线程的6种状态互相转换










