JUC 概述

并发,并行,串行

  • 并发:宏观上同时进行,微观上交替切换执行,单个 CPU 核心,靠快速切换任务
  • 并行:同一时刻,多个任务真正同时运行,多个 CPU 核心,每个核心独立跑一个任务
  • 串行:同一时刻只做一件事,做完一件再做下一件

线程

什么是线程

一个程序运行时,内部可以分成一个或多个线程,线程是CPU 执行任务的最小单位

创建线程的方式

实现 Runnable

java 复制代码
class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("Runnable 线程:" + Thread.currentThread().getName());
    }
}

public class Test {
    public static void main(String[] args) {
        MyRunnable r = new MyRunnable();
        Thread t = new Thread(r);
        t.start();
    }
}

继承 Thread

java 复制代码
class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("线程运行:" + Thread.currentThread().getName());
    }
}

public class Test {
    public static void main(String[] args) {
        MyThread t = new MyThread();
        t.start(); // 启动线程
    }
}

实现 Callable

java 复制代码
class MyCallable implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        System.out.println("Callable 线程运行");
        return 100; // 可以返回结果
    }
}

public class Test {
    public static void main(String[] args) throws Exception {
        FutureTask<Integer> task = new FutureTask<>(new MyCallable());
        Thread t = new Thread(task);
        t.start();
        
        // 获取返回值
        Integer res = task.get();
        System.out.println("结果:" + res);
    }
}

线程池创建

java 复制代码
public class Test {
    public static void main(String[] args) {
        // 创建线程池
        ExecutorService pool = Executors.newFixedThreadPool(3);
        
        // 提交任务
        pool.submit(() -> {
            System.out.println("线程池线程:" + Thread.currentThread().getName());
        });
        
        pool.shutdown(); // 关闭线程池
    }
}

线程的生命周期

  1. 新建,创建了一个线程对象,但是没有调用 start() 方法
  2. 就绪,调用了 start(),等着 CPU 分配时间片,一旦拿到 CPU,就开始执行 run()
  3. 阻塞,线程阻塞于锁
  4. 等待,主动无限期等别人唤醒,例如:wait() / join() / LockSupport.park()
  5. 定时等待,有时间限制的等待,例如:sleep(1000) / wait(1000) / join(1000)
  6. 终止,run() 执行完 / 异常退出

状态的流转关系

plaintext 复制代码
NEW → start() → RUNNABLE

RUNNABLE
   ↓ 抢锁失败
   BLOCKED → 拿到锁 → RUNNABLE

RUNNABLE
   ↓ wait()/join()
   WAITING → notify()/notifyAll() → RUNNABLE

RUNNABLE
   ↓ sleep(1000)
   TIMED_WAITING → 时间到 → RUNNABLE

RUNNABLE → 执行完毕 → TERMINATED

如何终止线程

stop

强制杀死线程,已弃用

interrupt
java 复制代码
public class Test {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> {
            try {
                while (!Thread.currentThread().isInterrupted()) {
                    System.out.println("运行中...");
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                // 收到中断信号,退出
                System.out.println("线程被中断终止");
            }
        });
        t.start();
        Thread.sleep(2000);
        t.interrupt(); // 中断
    }
}
相关推荐
MayBaymax3 小时前
MongoDB 索引与事务
java·数据库·mongodb
vx-程序开发3 小时前
【计算机毕设】django校园跑腿服务系统83141
java·数据库·vue.js·spring boot·spring·elasticsearch·django
勇气要爆发3 小时前
006.注解
java·注解
liuchangng3 小时前
Jev 模型研究:从生成式大模型到决策式模型——System One、RLCD 校准与采用边界
java·javascript·人工智能·python·深度学习
GPU实战笔记3 小时前
本地跑不动 llama.cpp,临时租云 GPU 怎么搭?从启动服务到环境复用
java·服务器·网络·人工智能·深度学习·llama
撸串-研究生3 小时前
SSM + Vue 线上作业批改系统:在线答题、文件提交与教师批改闭环90608
java·ssm·在线答题·作业批改·文件提交
一 乐3 小时前
养老院管理系统|基于springboot + vue养老院管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·毕业设计
wang_shu_mo_ran3 小时前
Spring MVC 常用注解和用法(二)——url,cookie,session
java·mvc
杨运交3 小时前
[074][示例]基于Redisson的分布式锁在定时任务中的实践与异常模拟
java·后端·spring
小刘在重生~3 小时前
Java Lock 显式锁案例|ReentrantLock 解决多线程安全问题(超详细实战)
java·笔记·面试