并发编程之java线程

一:创建线程

方法一:

@Slf4j
public class demo1 {
    public static void main(String[] args) {
        Thread t = new Thread("t1") {
            @Override
            public void run() {
                // 要执行的任务
                log.debug("hello");
            }
        };
        // 启动线程
        t.start();

        log.debug("run");
    }
}

方法二:Runnable类可以作为Thread构造函数的参数传入
在这里插入图片描述

@Slf4j
public class demo2 {
    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                // 要执行的任务
                log.debug("hello");
            }
        };
        // 创建线程对象
        Thread t = new Thread(r, "t2");
        // 启动线程
        t.start();
    }
}

方法二的lambda简化

@Slf4j
public class demo3 {
    public static void main(String[] args) {
        Runnable r = () -> { log.debug("hello"); };
        Thread t = new Thread(r, "t2");
        t.start();
    }
}

方法三:使用FutureTask类,FutureTask实现了Runnable接口,因此也可以传入Thread(Runnable target, String name)
在这里插入图片描述

@Slf4j
public class demo4 {
    public static void main(String[] args) throws Exception{
        FutureTask<Integer> task3 = new FutureTask<>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                log.debug("running");
                Thread.sleep(1000);
                return 100;
            }
        });

        new Thread(task3, "t3").start();
        // 主线程调用get方法时,主线程会等待t3线程返回值
        log.debug("结果是:{}", task3.get());
        log.debug("hello");
    }
}

二:线程运行原理

栈与栈帧:Java Virtual Machine Stacks (Java 虚拟机栈)

JVM 中由堆、栈、方法区所组成,其中栈内存其实就是给线程用的,每个线程启动后,虚拟
机就会为其分配一块栈内存。

  • 每个栈由多个栈帧(Frame)组成,对应着每次方法调用时所占用的内存
  • 每个线程只能有一个活动栈帧,对应着当前正在执行的那个方法

线程上下文切换:Thread Context Switch

因为以下一些原因导致 cpu 不再执行当前的线程,转而执行另一个线程的代码

  • 线程的 cpu 时间片用完
  • 垃圾回收
  • 有更高优先级的线程需要运行
  • 线程自己调用了 sleep、yield、wait、join、park、synchronized、lock 等方法

当 Context Switch 发生时,需要由操作系统保存当前线程的状态,并恢复另一个线程的状态,Java 中对应的概念就是程序计数器(Program Counter Register),它的作用是记住下一条 jvm 指令的执行地址,是线程私有的

  • 状态包括程序计数器、虚拟机栈中每个栈帧的信息,如局部变量、操作数栈、返回地址等
  • Context Switch 频繁发生会影响性能

三:常见方法

方法名static功能说明注意
start()启动一个新线程,在新的线程运行 run 方法中的代码start 方法只是让线程进入就绪,里面代码不一定立刻运行(CPU 的时间片还没分给它)。每个线程对象的start方法只能调用一次,如果调用了多次会出现IllegalThreadStateException
run()新线程启动后会调用的方法如果在构造 Thread 对象时传递了 Runnable 参数,则线程启动后会调用 Runnable 中的 run 方法,否则默认不执行任何操作。但可以创建 Thread 的子类对象,来覆盖默认行为
join()等待线程运行结束
join(long n)等待线程运行结束,最多等待 n毫秒
getId()获取线程长整型的 idid 唯一
getName()获取线程名
setName(String)修改线程名
getPriority()获取线程优先级
setPriority(int)修改线程优先级java中规定线程优先级是1~10 的整数,较大的优先级能提高该线程被 CPU 调度的机率
getState()获取线程状态Java 中线程状态是用 6 个 enum 表示,分别为:NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED
isInterrupted()判断是否被打断不会清除 打断标记
isAlive()线程是否存活(还没有运行完毕)
interrupt()打断线程如果被打断线程正在 sleep,wait,join 会导致被打断的线程抛出 InterruptedException,并清除 打断标记 ;如果打断的正在运行的线程,则会设置 打断标记 ;park 的线程被打断,也会设置 打断标记
interrupted()static判断当前线程是否被打断会清除 打断标记
currentThread()static获取当前正在执行的线程
sleep(long n)static让当前执行的线程休眠n毫秒,休眠时让出 cpu的时间片给其它线程
yield()static提示线程调度器让出当前线程对CPU的使用主要是为了测试和调试

1). start 与 run

public static void main(String[] args) {
   Thread t1 = new Thread("t1") {
       @Override
       public void run() {
          log.debug(Thread.currentThread().getName());
          FileReader.read(Constants.MP4_FULL_PATH); // 读取文件,耗时较长
       }
   };
   t1.run();
   log.debug("do other things ...");
}

输出:

19:39:14 [main] c.TestStart - main
19:39:14 [main] c.FileReader - read [1.mp4] start ...
19:39:18 [main] c.FileReader - read [1.mp4] end ... cost: 4227 ms
19:39:18 [main] c.TestStart - do other things ...

可见程序仍在 main 线程运行, FileReader.read() 方法调用还是同步的

public static void main(String[] args) {
   Thread t1 = new Thread("t1") {
       @Override
       public void run() {
          log.debug(Thread.currentThread().getName());
          FileReader.read(Constants.MP4_FULL_PATH); // 读取文件,耗时较长
       }
   };
   t1.start();
   log.debug("do other things ...");
}

输出:

19:41:30 [main] c.TestStart - do other things ...
19:41:30 [t1] c.TestStart - t1
19:41:30 [t1] c.FileReader - read [1.mp4] start ...
19:41:35 [t1] c.FileReader - read [1.mp4] end ... cost: 4542 ms

程序在 t1 线程运行, FileReader.read() 方法调用是异步的

因此可以得出:

  • 直接调用 run 是在主线程中执行了 run,没有启动新的线程
  • 使用 start 是启动新的线程,通过新的线程间接执行 run 中的代码

2). sleep 与 yield

sleep

  1. 调用 sleep 会让当前线程从运行状态进入 Timed Waiting 状态(阻塞)
  2. 其它线程可以使用 interrupt 方法打断正在睡眠的线程,这时 sleep 方法会抛出 InterruptedException
  3. 睡眠结束后的线程未必会立刻得到执行
  4. 建议用 TimeUnit 的 sleep 代替 Thread 的 sleep 来获得更好的可读性

yield

  1. 调用 yield 会让当前线程从 Running 进入 Runnable 就绪状态,然后调度执行其它线程
  2. 具体的实现依赖于操作系统的任务调度器
    @Test
    public void test5() {
        Runnable task1 = () -> {
            int count = 0;
            for (;;) {
                System.out.println("---->1 " + count++);
            }
        };
        Runnable task2 = () -> {
            int count = 0;
            for (;;) {
                 Thread.yield();
                System.out.println(" ---->2 " + count++);
            }
        };
        Thread t1 = new Thread(task1, "t1");
        Thread t2 = new Thread(task2, "t2");
        t1.start();
        t2.start();
    }

在这里插入图片描述

3).线程优先级

  • 线程优先级会提示(hint)调度器优先调度该线程,但它仅仅是一个提示,调度器可以忽略它
  • 如果 cpu 比较忙,那么优先级高的线程会获得更多的时间片,但 cpu 闲时,优先级几乎没作用

在这里插入图片描述
从源码可以看出,最小优先级是1,最大优先级是10

    @Test
    public void test5() {
        Runnable task1 = () -> {
            int count = 0;
            for (;;) {
                System.out.println("---->1 " + count++);
            }
        };
        Runnable task2 = () -> {
            int count = 0;
            for (;;) {
                System.out.println(" ---->2 " + count++);
            }
        };
        Thread t1 = new Thread(task1, "t1");
        Thread t2 = new Thread(task2, "t2");
        t1.setPriority(Thread.MIN_PRIORITY); // 最高优先级
        t2.setPriority(Thread.MAX_PRIORITY); // 最低优先级
        t1.start();
        t2.start();
    }

在这里插入图片描述
可见高优先级的线程执行时间更多。

4). join

    static int r = 0;
    @Test
    public void test7() {
        System.out.println("开始");
        Thread t1 = new Thread(() -> {
            System.out.println("开始");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("结束");
            r = 10;
        });
        t1.start();
        System.out.println("结果为: " + r);
        System.out.println("结束");
    }

在这里插入图片描述
那么如果现在有一个需求,就是主线程要获得子线程执行结束后的r的值,那么就需要主线程等子线程执行完,这时候就可以使用join方法:
在这里插入图片描述

在这里插入图片描述

    static int r1 = 0;
    static int r2 = 0;
    @Test
    public void test8() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            r1 = 10;
        });
        Thread t2 = new Thread(() -> {
            try {
                Thread.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            r2 = 20;
        });

        long start = System.currentTimeMillis();
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        long end = System.currentTimeMillis();
        System.out.println("r1: " + r1 + " r2: " + r2 + " cost: " + (end - start));
    }

很明显结果是这样的:
在这里插入图片描述
那如果t1和t2的join顺序调换,那么结果会是一模一样的,原因如下图:
在这里插入图片描述

5). interrupt

package com.eyes.thread.thread.method;

import org.junit.jupiter.api.Test;
import java.util.concurrent.locks.LockSupport;

public class Method {
    /**
     * interrupt打断阻塞线程
     */
    @Test
    public void test() throws InterruptedException {
        Thread t = new Thread(() -> {
            System.out.println("sleep....");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
              e.printStackTrace();
            };
        });
        t.start();
        Thread.sleep(1000);
        System.out.println("interrupt");
        t.interrupt();
        System.out.println("打断标记: " + t.isInterrupted());
    }

    /**
     * interrupt打断正常运行线程
     */
    @Test
    public void test2() throws InterruptedException {
        Thread t = new Thread(() -> {
            while(true) {
                Boolean interrupted = Thread.currentThread().isInterrupted();
                if(interrupted) {
                    System.out.println("被打断了,推出循环");
                    break;
                }
            }
        });
        t.start();
        Thread.sleep(1000);
        System.out.println("interrupt");
        t.interrupt();
    }

    /**
     * park方法
     */
    @Test
    public void test3() throws InterruptedException {
        Thread thread = new Thread(() -> {
            System.out.println("start.....");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("park....");
            LockSupport.park();
            System.out.println("resume.....");
        });
        thread.start();
        Thread.sleep(2000);
        System.out.println("unpark....");
        LockSupport.unpark(thread);
    }

    /**
     * interrupt打断park
     */
    @Test
    public void test4() throws InterruptedException {
        Thread t = new Thread(() -> {
            System.out.println("park...");
            LockSupport.park();

            System.out.println("unpark...");
            System.out.println("打断状态: " + Thread.currentThread().interrupted());

            LockSupport.park();
            System.out.println("again...");
        });
        t.start();

        t.sleep(1000);
        t.interrupt();
    }
}

/**
 * 设计模式之两阶段终止
 */
class TwoPhaseTermination {
    private Thread monitor;

    // 启动监控线程
    public void start() {
        monitor = new Thread(() -> {
            while(true) {
                Thread current = Thread.currentThread();
                if(current.isInterrupted()) {
                    System.out.println("料理后事");
                    break;
                }
                try {
                    Thread.sleep(1000);
                    System.out.println("执行监控记录");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        monitor.start();
    }

    // 停止监控线程
    public void stop() {
        monitor.interrupt();
    }
}

6). 过时方法

这些方法已过时,容易破坏同步代码块,造成线程死锁
在这里插入图片描述

7).守护线程

默认情况下,Java 进程需要等待所有线程都运行结束,才会结束。有一种特殊的线程叫做守护线程,只要其它非守护线程运行结束了,即使守护线程的代码没有执行完,也会强制结束。

    @Test
    public void test9() throws InterruptedException {
        System.out.println("开始程序");
        Thread t1 = new Thread(() -> {
            System.out.println("开始run");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("结束run");
        }, "daemon");
        // 设置该线程为守护线程
        t1.setDaemon(true);
        t1.start();
        Thread.sleep(1000);
        System.out.println("结束程序");
    }

在这里插入图片描述
可见“结束run”没有执行。

注意: 由于守护线程的终止是自身无法控制的,因此千万不要把IO、File等重要操作逻辑分配给它;因为它不靠谱;

那么守护线程的作用是什么?
举例, GC垃圾回收线程:就是一个经典的守护线程,当我们的程序中不再有任何运行的Thread,程序就不会再产生垃圾,垃圾回收器也就无事可做,所以当垃圾回收线程是JVM上仅剩的线程时,垃圾回收线程会自动离开。它始终在低级别的状态中运行,用于实时监控和管理系统中的可回收资源。

应用场景:

  • 来为其它线程提供服务支持的情况;
  • 在任何情况下,程序结束时,这个线程必须正常且立刻关闭,就可以作为守护线程来使用;反之,如果一个正在执行某个操作的线程必须要正确地关闭掉否则就会出现不好的后果的话,那么这个线程就不能是守护线程,而是用户线程。通常都是些关键的事务,比方说,数据库录入或者更新,这些操作都是不能中断的。

四:线程状态

操作系统层面来描述,线程有五种状态:
在这里插入图片描述

  • 【初始状态】仅是在语言层面创建了线程对象,还未与操作系统线程关联
  • 【可运行状态】(就绪状态)指该线程已经被创建(与操作系统线程关联),可以由 CPU 调度执行
  • 【运行状态】指获取了 CPU 时间片运行中的状态,当 CPU 时间片用完,会从【运行状态】转换至【可运行状态】,会导致线程的上下文切换
  • 【阻塞状态】如果调用了阻塞 API,如 BIO 读写文件,这时该线程实际不会用到 CPU,会导致线程上下文切换,进入【阻塞状态】等 BIO 操作完毕,会由操作系统唤醒阻塞的线程,转换至【可运行状态】,与【可运行状态】的区别是,对【阻塞状态】的线程来说只要它们一直不唤醒,调度器就一直不会考虑
    调度它们
  • 【终止状态】表示线程已经执行完毕,生命周期已经结束,不会再转换为其它状态‘

从 Java API 层面来描述,则有六种状态:
在这里插入图片描述

  • NEW 线程刚被创建,但是还没有调用 start() 方法
  • RUNNABLE 当调用了 start() 方法之后,注意,Java API 层面的 RUNNABLE 状态涵盖了 操作系统 层面的【可运行状态】、【运行状态】和【阻塞状态】(由于 BIO 导致的线程阻塞,在 Java 里无法区分,仍然认为是可运行)
  • BLOCKED , WAITING , TIMED_WAITING 都是 Java API 层面对【阻塞状态】的细分
  • TERMINATED 当线程代码运行结束
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值