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(); // 中断
    }
}
相关推荐
ikgy1 天前
JAVA EE:4.多线程核心组件实战
java·java-ee
小七在进步1 天前
string的实现(3)
开发语言·c++·笔记·visual studio
杨凯凡1 天前
IT日报|2026-11-19:Oracle Java 紧急补丁、Optimizely 供应链攻击、GitHub 安全评估升级
java·oracle·github
JasonChen@6661 天前
2.Tomcat 安装部署与一键自动化脚本实战
java·tomcat
专注仿真1 天前
基于 AFSIM 的智能体训练:多智能体强化学习篇 —— QTRAN 算法实战
开发语言·python·算法·php·强化学习·afsim智能体·仿真训练
SimonKing1 天前
零 OCR 依赖!Firecrawl 这个 Rust 库把 Word / PPT / Excel 全变成 Markdown
java·后端·程序员
Rain的Java大神之路1 天前
别被 ChatGPT 的打字机效果骗了:一字一字蹦,才是 LLM 自回归的命门(附大厂 Java 流式落地)
java·后端·面试
渣渣盟1 天前
狂命爆肝99天,共52K字的JAVA学习笔记奉上,JAVA从入门到精通一文搞定,一文在手JAVA无忧
java·笔记·学习
Funlang1 天前
RISC-V 上的 Fun:第四套机器码
开发语言·risc-v·龙芯
星落梦生1 天前
Maven高级(9)
java·maven