多线程基础

1. 继承 Thread 类 重写 run 方法 启动调用 start 方法 缺点 不能继承其他类 优点简单

2. 定义任务类继承 Runnable 接口 实现 run 方法    MyRunable 为自定义的任务类  优点可以继承其他类 

Runnable t = new MyRunable();
new Thread(t).start();

3. JDK 5.0 提供了 Callable接口 和 FutureTask类来实现 优点 可以返回线程执行的结果 

 1. 创建任务对象
  定义一个类实现Callable接口,重写call方法,封装要做的事情,和要返回的数据。
  把 Callable类型的对象封装成FutureTask(线程任务对象)。
2.把线程任务对象交给Thread对象。
3.调用Thread对象的start方法启动线程。
4.线程执行完毕后,通过 FutureTask 对象的get方法获取线程任务执行结果。
Callable<String> t = new MyCallable();
FutureTask<String> task = new FutureTask<>(t);
Thread thread = new Thread(task);
thread.start();
String res = task.get();
System.out.println(res);

4. 线程同步(解决线程安全问题)

  让多个线程依次访问共享资源,这样就解决线程安全问题  加锁

  方式一:同步代码块(同步锁)

// 静态方法建议用类名作为锁
    public static void test() {

        synchronized (Account.class) {

        }
    }

    public void drawMoney(double money) {

        String threadName = Thread.currentThread().getName();

        // this正好代表共享资源 实例方法建议用this作为锁对象
        synchronized (this) {
            if (this.money >= money) {
                System.out.println(threadName + "来取了" + money + "元成功");
                this.money -= money;
                System.out.println(threadName +  "余额" + this.money);
            } else {
                System.out.println(threadName + "来取钱,钱不足");
            }
        }
    }

  方法二:同步方法

// 同步方法 实例方法 隐含用this作为锁
    public synchronized void drawMoney(double money) {

        String threadName = Thread.currentThread().getName();

        if (this.money >= money) {
            System.out.println(threadName + "来取了" + money + "元成功");
            this.money -= money;
            System.out.println(threadName +  "余额" + this.money);
        } else {
            System.out.println(threadName + "来取钱,钱不足");
        }

    }

  方式三:Lock锁

  Lock锁是JDK5开始提供的一个新的锁定操作,通过它可以创建出锁对象进行加锁和解锁,更灵活,更方便,更强大。

  Lock是接口,不能直接实例化,可以采用它的实现类 ReentrantLock 来构建 Lock 锁对象。

  

/**
     * 创建一个锁对象
     */
    private final Lock lk = new ReentrantLock();

    public void drawMoney(double money) {

        String threadName = Thread.currentThread().getName();

        try {
            // 加锁
            lk.lock();
            if (this.money >= money) {
                System.out.println(threadName + "来取了" + money + "元成功");
                this.money -= money;
                System.out.println(threadName +  "余额" + this.money);
            } else {
                System.out.println(threadName + "来取钱,钱不足");
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            // 解锁
            lk.unlock();
        }
    }

5. 线程通信

  当多个线程共同操作共享资源时,线程 间通过某种方式互相告诉自己的状态,以相互协调,并避免无效的资源争夺。

public class Test6 {

    public static void main(String[] args) {
        Desk desk = new Desk();

        // 三个生产者线程
        new Thread(() -> {
            while (true) {
                desk.put();
            }
        }, "厨师1").start();

        new Thread(() -> {
            while (true) {
                desk.put();
            }
        }, "厨师2").start();

        new Thread(() -> {
            while (true) {
                desk.put();
            }
        }, "厨师3").start();


        // 两个消费者线程
        new Thread(() -> {
            while (true) {
                desk.get();
            }
        }, "吃货1").start();

        new Thread(() -> {
            while (true) {
                desk.get();
            }
        }, "吃货2").start();

    }
}
public class Desk {

    private List<String> list = new ArrayList<>();

    // 放一个包子的方法
    // 厨师1 厨师2 厨师3
    public synchronized void put() {
        try {
            String name = Thread.currentThread().getName();
            // 判断是否有包子
            if (list.size() == 0) {
                list.add(name + "做的肉包子");
                System.out.println(name + "做了一个肉包子~~");
                Thread.sleep(2000);
                // 等待自己,唤醒别人 要使用当前锁对象
                this.notifyAll();
                this.wait();
            } else {
                // 等待自己,唤醒别人 要使用当前锁对象
                this.notifyAll();
                this.wait();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 吃货1 吃货2
    public synchronized void get() {

        try {
            String name = Thread.currentThread().getName();
            if (list.size() == 1) {
                // 有包子,吃了
                System.out.println(name + "吃了:" + list.get(0));
                list.clear();
                Thread.sleep(1000);
                this.notifyAll();
                this.wait();
            } else {
                // 没有包子
                this.notifyAll();
                this.wait();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 6. 线程池

  JDK5.0提供了代表线程池的接口:ExecutorService

   获取线程对象

   方式一:使用 ExecutorService 的实现类 ThreadPoolExecutor 自创建一个线程池对象。

   方式二:使用 Executors (线程池工具类)调用方法返回不同特点的线程池对象。

public ThreadPoolExecutor(int corePoolSize, // 核心线程数量
                              int maximumPoolSize,  // 最大线程数
                              long keepAliveTime,  // 临时线程的存活时间
                              TimeUnit unit,  // 指定临时线程存活的时间单位(秒,分,时,天)
                              BlockingQueue<Runnable> workQueue,  // 指定线程池的任务队列
                              ThreadFactory threadFactory,  // 指定线程池的线程工厂
                              RejectedExecutionHandler handler) {}  // 指定线程池的任务拒绝策略(线程都在忙,任务队列也满了的时候,新任务来了该怎么处理)

  创建线程池对象

     // 创建一个线程池对象
        ExecutorService pool = new ThreadPoolExecutor(3, 5, 8,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(4),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

  线程池的主要事项:

    1.临时线程什么时候创建?

      新任务提交时发现核心线程都在忙,任务队列也满了,并且还可以创建临时线程,此时才会创建临时线程。

    2.什么时候会开始拒绝新任务?

      核心线程和临时线程都在忙,任务队列也满了,新的任务过来的时候才会开始拒绝任务。

  新任务拒绝策略:

    ThreadPoolExecutor.AbortPolicy 丢弃任务并抛出 RejectedExecutionException异常。是默认的策略

    ThreadPoolExecutor.DiscardPolicy 丢弃任务,但是不抛出异常 这是不推荐的做法

    ThreadPoolExecutor.DiscardOldestPolicy 抛出队列中等待最久的任务 然后把当前任务加入队列中

    ThreadPoolExecutor.CallerRunsPolicy 由主线程负责调用任务的run()方法从而绕过线程池直接执行

// 创建一个线程池对象
        ExecutorService pool = new ThreadPoolExecutor(3, 5, 8,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(4),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

        MyRunnable2 runnable2 = new MyRunnable2();

        // 线程池会自动创建一个新 线程,自动处理这个任务
        pool.execute(runnable2);
        pool.execute(runnable2);
        pool.execute(runnable2);
        pool.execute(runnable2);
        pool.execute(runnable2);
        pool.execute(runnable2);
        pool.execute(runnable2);
        pool.execute(runnable2);
        pool.execute(runnable2);
        pool.execute(runnable2);

        // 等待线程池的任务全部执行完毕后,在关闭线程池
        pool.shutdown();

        // 立即关闭线程池,不管任务是否执行完成
        // pool.shutdownNow();

  使用线程池处理 Callable 任务

// 创建一个线程池对象
        ExecutorService pool = new ThreadPoolExecutor(3, 5, 8,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(4),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

        // 使用线程池处理 Callable 任务
        Future<String> f1 = pool.submit(new MyCallable2(100));
        Future<String> f2 = pool.submit(new MyCallable2(200));
        Future<String> f3 = pool.submit(new MyCallable2(300));
        Future<String> f4 = pool.submit(new MyCallable2(400));

        System.out.println(f1.get());
        System.out.println(f2.get());
        System.out.println(f3.get());
        System.out.println(f4.get());

  ExecutorService 的常用方法

void execute(Runnable command); // 执行任务/命令,没有返回值,一般用来执行 Runnable 任务
Future<T> submit(Callable<T> task); // 执行任务,返回未来任务对象获取线程结果,一般拿来执行 Callable 任务
void shutdown(); // 等任务执行完毕后关闭线程池
List<Runnable> shutdownNow(); // 立刻关闭,停止正在执行的任务,并返回队列中未执行的任务

  Executors 是一个线程池的工具类,提供了很多静态方法用于返回不同特点的线程池对象。

    Executors 的方法的底层,都是通过线程池的实现类 ThreadPoolExecutor 创建的线程池对象。

// 通过 Executors 创建线程池对象
        ExecutorService pool = Executors.newFixedThreadPool(3);

        ExecutorService pool2 = Executors.newSingleThreadExecutor();

  核心线程数应该配置多少

    计算密集型的任务:核心线程数量 = CPU的核数 + 1  例如:8核 应该配置 9

    IO密集型的任务:核心线程数量 = CPU核数 * 2 例如:8核 应该配置 16

 进程:正在运行的程序(软件)就是一个独立的进程。

    线程是属于进程的,一个进程中可以同时运行多个线程。

    进程中的多个线程其实是并发和并行执行的。

并发的含义

    进程中的线程是由cpu负责调度执行的,但cpu能同时处理线程的数量有限,为了保证全部线程都能往前执行,cpu会轮询为系统的每个线程服务,由于cpu切换的速度很快,给我们的感觉这些线程在同时执行,这就是并发。

并行的理解

    在同一时刻上,同时有多个线程在被cpu调度执行。

线程的生命周期(各种状态)

    java线程的状态,java总共定义了6种状态,6种状态都定义在 Thread 类的内部枚举类中。

    New 新建 --> Runnable 可运行 --> Teminated 被终止 --> Blocked 锁阻塞 --> Waiting 无限等待 --> Timed Waiting 计时等待

 

posted @ 2023-07-13 23:23  record-100  阅读(24)  评论(0)    收藏  举报