线程基础知识点

本文详细解释了线程与进程的区别,进程与线程的并发与并行概念,线程的四种创建方式,线程状态及其转换,join、notify和notifyAll的使用,wait和sleep的区别,以及停止线程的方法。
摘要由CSDN通过智能技术生成

1. 线程和进程的区别?

程序由指令数据组成,但这些指令要运行,数据要读写,就必须将指令加载至 CPU,数据加载至内存。在指令运行过程中还需要用到磁盘、网络等设备。进程就是用来加载指令、管理内存、管理 IO 的。
当一个程序被运行,从磁盘加载这个程序的代码至内存,这时就开启了一个进程
一个线程就是一个指令流,将指令流中的一条条指令以一定的顺序交给 CPU 执行
一个进程之内可以分为一到多个线程。

二者对比

  • 进程是正在运行程序的实例,进程中包含了线程,每个线程执行不同的任务
  • 不同的进程使用不同的内存空间,在当前进程下的所有线程可以共享内存空间
  • 线程更轻量,线程的上下文切换成本一般上要比进程上下文切换低(上下文切换指的是从一个线程切换到另一个线程)

2. 并行与并发的区别?

单核 CPU

  • 单核 CPU 下线程实际还是串行执行的
CPU时间片 1时间片 2时间片 3
core线程 1线程 2线程 3

每个时间片只能由 1 个线程执行。

  • 操作系统中有一个组件叫做任务调度器,将 cpu 的时间片(windows 下时间片最小约为 15 毫秒)分给不同的程序使用,只是由于 cpu 在线程间(时间片很短)的切换非常快,人类感觉是同时运行的。
  • 总结为一句话就是:微观串行,宏观并行。(感觉是并行,实际是串行)
  • 一般会将这种线程轮流使用 CPU 的做法称为并发(concurrent)

多核 CPU

每个核(core)都可以调度运行线程,这时候线程可以是并行的。

区别

并发(concurrent)是同一时间应对(dealing with)多件事情的能力
并行(parallel)是同一时间动手做(doing)多件事情的能力

3. 线程创建的方式有哪些?

共有 4 种方式可以创建线程,分别是:

  1. 继承 Thread 类
  2. 实现 runnable 接口
  3. 实现 Callable 接口
  4. 线程池创建线程

继承 Thread 类

public class MyThread extends Thread{
    @Override
    public void run(){
        System.out.println("run");
    }
    public static void main(String[] args){
        // 创建MyThread对象
        MyThread t = new MyThread();
        // 调用start方法启动线程
        t.start();
    }
}

实现 Runnable 接口

public class MyRunnable implements Runnable{
    @Override
    public void run(){
        System.out.println("run");
    }
    public static void main(String[] args){
        // 创建MyRunnable对象
        MyRunnable mr = new MyRunnable();
        // 创建Thread对象
        MyThread t = new MyThread(mr);
        // 调用start方法启动线程
        t.start();
    }
}

实现 Callable 接口

public class MyCallable implements Callable<String>{
    @Override
    public String call()throws Exception{
        System.out.println("run");
        return "ok";
    }
    public static void main(String[] args) throws ExecutionException,InterruptedException{
        // 创建MyRunnable对象
        MyCallable mr = new MyCallable();
        // 创建Future Task
        FutureTask<String> ft = new FutureTask<String>(mr);
        // 创建Thread对象
        MyThread t = new MyThread(mr);
        // 调用start方法启动线程
        t.start();
        // 调用ft的get方法获取线程执行结果;
        String result = ft.get();
    }
}

注意:

  • 接口后面的泛型和 call 方法的返回值一样。
  • call 方法内就是线程要执行的内容。
  • 这种方式对于需要线程返回结果的很合适。

线程池创建线程

public class MyExecutors implements Runnable{
    @Override
    public void run(){
        System.out.println("run");
    }
    public static void main(String[] args){
        // 创建线程池对象
        ExecutorService threadPool = Executors.newFixedPool(3);
        threadPool.submit(new MyExecutors());
        // 关闭线程池
        threadPool.shutdown();
    }
}

追问:Runnable 和 Callable 的区别

  1. Runnable 接口 run 方法没有返回值。
  2. Callable 接口 call 方法有返回值,是个泛型,和 Future、FutureTask 配合可以用来获取异步执行的结果。
  3. Callable 接口的 call 方法允许抛出异常;而 Runnable 接口的 run 方法的异常只能在内部消化,不能继续上抛。

追问:在启动线程的时候,可以使用 run 方法吗?run() 和 start()有什么区别?

启动的线程的时候不可以使用 run 方法。

  • start(): 用来启动线程,通过该线程调用 run 方法执行 run 方法中所定义的逻辑代码。start 方法只能被调用一次。
  • run():封装了要被线程执行的代码,就是一个普通的方法,可以被调用多次。

4. 线程包括哪些状态,状态之间是如何变化的?

线程的状态可以参考 JDK 中的 Thread 类中的枚举 State

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;
    }


面试回答参考

  1. 线程包括哪些状态?

新建(NEW)、可执行(RUNNABLE)、阻塞(BLOCKED)、等待(WAITING)、时间等待(TIMED_WAITING)、终止(TERMINATED)

  1. 线程状态之间是如何变化的
  • 创建线程对象是新建状态
  • 调用了 start() 方法转变为可执行状态
  • 线程获取到了 CPU 的执行权,执行结束是终止状态
  • 在可执行状态的过程中,如果没有获取 CPU 的执行权,可能会切换其他状态
    • 如果没有获取锁(synchronized 或 lock)进入**阻塞状态,**获得锁再切换为可执行状态
    • 如果线程调用了 wait() 方法进入等待状态,其他线程调用 notify() 唤醒后可切换为可执行状态
    • 如果线程调用了 sleep(50)方法,进入计时等待状态,到时间后可切换为可执行状态

5. 线程按顺序执行 join、notify 和 notifyall 的区别?

新建 T1、T2、T3 三个线程,如何保证它们按照顺序执行?

可以使用线程中的 join 方法解决。
join() 等待线程运行结束。例如,调用 t.join(),阻塞调用此方法的线程,使其进入 timed_waiting 状态,直到线程 t 执行完成后,此线程再继续执行。

public class JoinTest {
    public static void main(String[] args) {
        // 创建线程对象
        Thread t1 = new Thread(()->{
            System.out.println("t1");
        });
        Thread t2 = new Thread(()->{
            try {
                t1.join();  // 加入线程t1,只有t1线程执行完毕后,再次执行该线程
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("t2");
        });
        Thread t3 = new Thread(()->{
            try {
                t2.join();  // 加入线程t2,只有t2线程执行完毕后,再次执行该线程
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("t3");
        });
        // 启动线程
        t3.start();
        t2.start();
        t1.start();
    }
}
// 执行结果
t1
t2
t3

notify 和 notifyAll 有什么区别?

  • notifyAll:唤醒所有 wait 的线程
  • notify:只随机唤醒一个 wait 线程

6. Java 中 wait 和 sleep 方法的不同?

共同点
wait(),wait(long) 和 sleep(long) 的效果都是让当前线程暂时放弃 CPU 的使用权,进入阻塞状态。
不同点

  1. 方法归属不同
  • sleep(long) 是 Thread 的静态方法
  • 而 wait(),wait(long)都是 Object 的成员方法,每个对象都有
  1. 醒来时机不同
  • 执行 sleep(long) 和 wait(long) 的线程都会在等待相应的毫秒后醒来
  • wait(long) 和 wait() 还可以被 notify 唤醒,wait() 如果不唤醒就一直等下去
  • 它们都可以被打断唤醒
  1. 锁特性不同(重点)
  • wait 方法的调用必须先获取 wait 对象的锁(比如配合 synchronized 锁使用),而 sleep 则无此限制
  • wait 方法执行后会释放对象锁,允许其它线程获得该对象锁
  • sleep 方法如果在 synchronized 代码块中执行,并不会释放对象锁

7. 如何停止一个正在运行的线程?

有三种方式可以停止线程

  • 使用退出标志,使线程正常退出,也就是当 run 方法完成后线程终止
public class MyInterrupt1 extends Thread{
    volatile boolean flag = false;  // 线程执行的退出标记

    @Override
    public void run(){
        while(!flag){
            System.out.println("MyThread...run...");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        // 创建MyThread对象
        MyInterrupt1 t1 = new MyInterrupt1();
        t1.start();

        // 主线程休眠6秒
        Thread.sleep(6000);

        // 更改标记为true
        t1.flag = true;
    }
}
// 执行结果
MyThread...run...
MyThread...run...
  • 使用 stop 方法强行终止(不推荐,已作废)
  • 使用 interrupt 方法中断线程
    • 打断阻塞的线程(sleep、wait、join)的线程,线程会抛出 InterruptedException 异常
    • 打断正常的线程,可以根据打断状态来标记是否退出线程
public class MyInterrupt3 {
    public static void main(String[] args) throws InterruptedException {
        // 1. 打断阻塞的线程
        Thread t1 = new Thread(()->{
            System.out.println("t1 正在运行。。。");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "t1");
        t1.start();
        Thread.sleep(500);
        t1.interrupt();
        System.out.println(t1.isInterrupted());
        // 2. 打断正常的线程
//        Thread t2 = new Thread(()->{
//            while(true){
//                Thread current = Thread.currentThread();
//                boolean interrupted = current.isInterrupted();
//                if(interrupted){
//                    System.out.println("打断状态:"+ interrupted);
//                    break;
//                }
//            }
//        },"t2");
//        t2.start();
//        Thread.sleep(500);
//        t2.interrupt();
    }
}
//1执行结果
t1 正在运行。。。
false
Exception in thread "t1" java.lang.RuntimeException: java.lang.InterruptedException: sleep interrupted
	at MyInterrupt3.lambda$main$0(MyInterrupt3.java:9)
	at java.lang.Thread.run(Thread.java:750)
Caused by: java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at MyInterrupt3.lambda$main$0(MyInterrupt3.java:7)
	... 1 more
//2执行结果
打断状态:true
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值