首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Java 多线程 (Part1: Java线程基础)

Java 多线程 (Part1: Java线程基础)

作者头像
JiahuiZhu1998
修改于 2023-06-15 16:09:03
修改于 2023-06-15 16:09:03
36200
代码可运行
举报
运行总次数:0
代码可运行

Java Thread 实现/创建方式

  • 使用 Class Thread
  • 使用 Interface Runnable (No Return Value 无返回值)
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
//  最简单的 Thread 和 Runnable 的配套使用
Runnable task = () -> {
    String threadName = Thread.currentThread().getName();
    System.out.println("Hello " + threadName);
}; // 用 Lambda 表达式实现 Runnable接口

task.run();

Thread thread = new Thread(task);
thread.start();

System.out.println("Done!");
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
//  带 thread sleep 的 Thread 和 Runnable 的配套使用
Runnable runnable = () -> {
    try {
        String name = Thread.currentThread().getName();
        System.out.println("Foo " + name);
        TimeUnit.SECONDS.sleep(1);
        System.out.println("Bar " + name);
    }
    catch (InterruptedException e) {
        e.printStackTrace();
    }
};

Thread thread = new Thread(runnable);
thread.start();

  • 使用 ExecutorService (线程池接口)
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
// 最简单的 ExecutorService 使用的例子
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
    String threadName = Thread.currentThread().getName();
    System.out.println("Hello " + threadName);
});

// 以下是ScheduledExecutorService 的使用, 也是ExecutorService的一种
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
// => Hello pool-1-thread-1

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
// ExecutorService 使用 shutdown 和 shutdownNow 这两个方法去 Interrupt Running线程
try {
    System.out.println("attempt to shutdown executor");
    executor.shutdown();
    executor.awaitTermination(5, TimeUnit.SECONDS);
}
catch (InterruptedException e) {
    System.err.println("tasks interrupted");
}
finally {
    if (!executor.isTerminated()) {
        System.err.println("cancel non-finished tasks");
    }
    executor.shutdownNow();
    System.out.println("shutdown finished");
}
  • 使用 Callable<Class> (和 Runnable 一样也是一个Interface) ((Has Return Value 有返回值) 有返回值的Runnable
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
// 使用 Callable的最简单例子, 使用 sleep 可以让thread运行的更加久
Callable<Integer> task = () -> {
    try {
        TimeUnit.SECONDS.sleep(1);
        return 123;
    }
    catch (InterruptedException e) {
        throw new IllegalStateException("task interrupted", e);
    }
};
  • 使用 Future (和 Runnable 一样也是一个Interface)。预约排号的接口
  • 使用线程池 ( 下方代码有 newFixedThreadPool 线程池)
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
// 使用 Future 的最简单例子
Runnable task = () -> {
    String threadName = Thread.currentThread().getName();
    System.out.println("Hello " + threadName);
};
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<Integer> future = executor.submit(task);

System.out.println("future done? " + future.isDone());

Integer result = future.get();

System.out.println("future done? " + future.isDone());
System.out.print("result: " + result);

Java ThreadPool 线程池有哪些

一共有4种线程池

  1. newCachedThreadPool 可缓存线程池, 线程闲置60s便会被回收
  2. newFixedThreadPool 定长线程池, 线程闲置不会被回收
  3. newScheduledThreadPool 定时任务线程池, 核心线程闲置立刻被回收
  4. newSingleThreadExecutor 只有唯一线程的线程池, 支持 FIFO, LIFO; 如果唯一线程dead, 会new 一个新线程

Java Thread LifeCycle 线程的生命周期

  1. New 新建
  2. Runnable 就绪
  3. Blocked 阻塞
  4. Waiting 等待
  5. Timed Waiting 使用 timeout时间点的等待
  6. Terminated 终止
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
// Java program to demonstrate thread states
// Java 生命周期的 例子
class thread implements Runnable {
    public void run()
    {
        // moving thread2 to timed waiting state
        try {
            Thread.sleep(1500);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
 
        System.out.println(
            "State of thread1 while it called join() method on thread2 -"
            + Test.thread1.getState());
        try {
            Thread.sleep(200);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
 
public class Test implements Runnable {
    public static Thread thread1;
    public static Test obj;
 
    public static void main(String[] args)
    {
        obj = new Test();
        thread1 = new Thread(obj);
 
        // thread1 created and is currently in the NEW
        // state.
        System.out.println(
            "State of thread1 after creating it - "
            + thread1.getState());
        thread1.start();
 
        // thread1 moved to Runnable state
        System.out.println(
            "State of thread1 after calling .start() method on it - "
            + thread1.getState());
    }
 
    public void run()
    {
        thread myThread = new thread();
        Thread thread2 = new Thread(myThread);
 
        // thread1 created and is currently in the NEW
        // state.
        System.out.println(
            "State of thread2 after creating it - "
            + thread2.getState());
        thread2.start();
 
        // thread2 moved to Runnable state
        System.out.println(
            "State of thread2 after calling .start() method on it - "
            + thread2.getState());
 
        // moving thread1 to timed waiting state
        try {
            // moving thread1 to timed waiting state
            Thread.sleep(200);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(
            "State of thread2 after calling .sleep() method on it - "
            + thread2.getState());
 
        try {
            // waiting for thread2 to die
            thread2.join();
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(
            "State of thread2 when it has finished it's execution - "
            + thread2.getState());
    }
}

Java Thread 线程终止的方式

  1. 正常运行结束
  2. 用 exit flag boolean值 , 用 exit flag 当作 while loop 判断条件,判断条件为false时,线程终止
  3. 用 Interrupt 结束 当 Thread 处于 Blocked,使用 interrupt(), 并 catch InterrupttedException,最后 break 跳出循环结束thread 当 Thread不处于 Blocked, 使用 interrupt() 中 isInterrupted() 判断loop 是否结束, 和上方exit flag boolean原理一样
  4. 用 stop 结束 (线程不安全) thread.stop() 会释放所有Lock并破坏数据, 不建议使用

Java Thread 中 start, run, sleep, wait 分别是什么

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Thread thread = new Thread(new Runnable);
thread.start(); // thread 被开启, 进入 Runnable 就绪状态
thread.run(); // thread 被分配到CPU时间片后, 就会执行 thread.run() 运行线程
thread.sleep(1); // thread 的 static method, 让thread睡眠, 不释放Lock, 其他thread不能访问
thread.wait(); // thread 的 Object method, 让thread进入等待池, 释放Lock, 其他thread可以访问
// wait() 被使用后, 用 notify() 或者 notifyAll() 进行唤醒 

Java 后台线程是什么

又叫 守护线程, 用 setDaemon(true) 设置; gc thread(垃圾回收线程) 就是一种守护线程; 守护线程在 JVM里面进行工作

Java 线程的基本方法

线程状态图(包含状态机切换方法)
线程状态图(包含状态机切换方法)
  1. Wait 线程等待 使用wait 进入 Waiting 状态
  2. Sleep 线程睡眠 使用sleep 进入 Timed Wating状态
  3. Yield 线程让步 使用yield 让出 CPU执行时间片
  4. Interrupt 线程中断 使用interrupt 将 thread 从 RUNNING 变成 Terminated
  5. Join 等待其他线程Terminated 使用Join,将 thread 从Running 变成Blocked,等待其他thread Terminated
  6. Notify 线程唤醒 使用 notify 将 thread 从 Waiting /Timed Waiting 变成 Running (只唤醒一个线程)
  7. 其他线程中的函数 7.1 sleep() 强迫thread sleep 7.2 isAlive() 判断thread 是否存活 7.3 join() 等待线程终止 7.4 activeCount() 活跃的thread 数量 7.5 enumerate() 枚举所有thread 7.6 currentThread() 当前thread 7.7 isDaemon() 是否是守护thread 7.8 setDaemon() 设置为守护thread 7.9 setName() 设置 name of thread 7.10 wait() 强迫 thread wait

JAVA 线程的上下文切换 (Context Switch)

CPU上执行多任务,任务状态保存,再加载,这个过程称为上下文切换

线程上下文切换
线程上下文切换
  • Process 进程
  • Context 上下文: 某一时间点 CPU register和pc的内容
  • register
  • pc --- 专用的 register
  • PCB (Process Control Block ). --- 在上下文切换中保存信息在PCB
  • 上下文切换 --- 挂起一个process,存储状态(上下文),找到下一个存储状态(上下文),恢复对应process,切换成功

JAVA 线程上下文切换原因

  1. 当前任务时间片用完,cpu调度下一个任务
  2. 当前任务被阻塞,cpu调度下一个任务
  3. 多个任务抢占Lock,没有抢到Lock,被挂起,继续下一任务
  4. 代码挂起任务,让出cpu时间
  5. Hardware Interrupt

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
暂无评论
推荐阅读
第一个免费可用的智能Agent产品全量上线,中国公司智谱打造,推理模型比肩R1
我们来看一个非常经典的案例:只需要输出你想讨论的话题,AI 就能自动去小红书、知乎等平台上深度查询、总结完整报告,并转化为面向大众的传播内容。短短 14 天里,AI 孵化出了一个 5000 多个粉丝的小红书账号,还接到了商单。
机器之心
2025/04/01
3670
第一个免费可用的智能Agent产品全量上线,中国公司智谱打造,推理模型比肩R1
比 R1 快 8 倍、价格仅 3%,智谱新推理模型来袭,能让免费智能体自己赚钱!张鹏:Agent 也有 Scaling Law
刚刚,智谱推出最新的 AutoGLM 沉思模型,不仅具备深度研究能力(Deep Research),还能实现实际操作(Operator)。并且,这个会“边想边干”的智能体还能自己接单赚到钱。
深度学习与Python
2025/04/05
2020
比 R1 快 8 倍、价格仅 3%,智谱新推理模型来袭,能让免费智能体自己赚钱!张鹏:Agent 也有 Scaling Law
AutoGLM沉思:像人一样的深度思考+动手执行,让复杂问题迎刃而解,而且全免费
如果你是一个自媒体博主,你是否遇到这样的情况,因为白天上班工作忙,晚上下班还要勤勤恳恳的去运营自己的账号,一天的劳累已经让你冒火星子?
AIGC新知
2025/04/01
6100
AutoGLM沉思:像人一样的深度思考+动手执行,让复杂问题迎刃而解,而且全免费
智谱 GLM 新成员开源:高性能、推理快,体验入口“z.ai”免费开放
继智谱在上个月发布了他们的AutoGLM沉思全新智能体,在AI圈子引起广泛的反向,很多人纷纷使用AutoGLM沉思去完成自己工作中的一些任务,如写研究报告、行业调研等等。
AIGC新知
2025/04/16
4620
智谱 GLM 新成员开源:高性能、推理快,体验入口“z.ai”免费开放
智谱发布AutoGLM沉思版,国产DeepResearch来了,人人皆免费。
说真的,即使玩过了这么多的DeepResearch产品,我也没想到,他们能扔出个这么个有趣的玩意。
数字生命卡兹克
2025/04/14
8930
智谱发布AutoGLM沉思版,国产DeepResearch来了,人人皆免费。
考研数学得126分、还能编写小游戏,智谱首个推理模型来了,人人免费用
2024 年的最后一天,智谱 GLM 模型家族迎来了一位新成员——GLM-Zero 的初代版本 GLM-Zero-Preview,主打深度思考与推理。
机器之心
2025/02/03
1880
考研数学得126分、还能编写小游戏,智谱首个推理模型来了,人人免费用
又一AI利器!智谱发布全新推理大模型,速度快8倍,价格比DeepSeek-R1更低~
现在的大模型多如牛毛,LLaMA、Qwen、Bert等等,根本学不过来,甚至有的卷王还看Transform源码,这对于一般人来说学习曲线太长了。
派大星的数据屋
2025/04/18
1960
又一AI利器!智谱发布全新推理大模型,速度快8倍,价格比DeepSeek-R1更低~
AI现场发了2万红包,打开了大模型Act时代
最近一段时间,大模型领域正在经历智能体(AI Agent)引发的革命。Anthropic 推出的升级版 Claude 3.5 Sonnet,一经推出即引爆了 AI 圈。
机器之心
2025/02/14
1480
AI现场发了2万红包,打开了大模型Act时代
智谱Agent抢跑OpenAI,GLM-PC一句话搞定一切!网友:有AGI那味了
想象这样一个场景:微信上给xxx发送祝福语,再给他发送一个新春图片和一个新春祝贺视频。
新智元
2025/02/15
1520
智谱Agent抢跑OpenAI,GLM-PC一句话搞定一切!网友:有AGI那味了
智谱AI全新发布Agent家族,用AI操控一切不再是梦了。
甚至,还抢到了AI给大家发出的200元红包,只能说,谢谢AutoGLM,谢谢老板。
数字生命卡兹克
2025/04/14
1540
智谱AI全新发布Agent家族,用AI操控一切不再是梦了。
智谱AI深夜上线全新Agent GLM-PC,再见仍是巅峰。
2024年10月25日,智谱在CNCC发布了第一款手机自主人工智能,AutoGLM,直接在行业内和金融市场上掀起了风暴。
数字生命卡兹克
2025/04/14
1480
智谱AI深夜上线全新Agent GLM-PC,再见仍是巅峰。
智谱AI推出GLM-4,性能逼近ChatGPT-4
随着人工智能技术的持续发展,神经网络的参数数量已经从Alexnet的6000万个增长到OpenAI GPT-3的1750亿个,人工智能已进入大模型时代。ChatGPT、GLM-4、Claude3等大模型不断涌现,本文将详细介绍智谱AI所推出的GLM-4大模型,分析其背景、性能、应用等。
存内计算开发者
2024/06/14
8821
智谱AI推出GLM-4,性能逼近ChatGPT-4
AutoGLM的一小步,人机交互进化的一大步
55年前,左脚刚刚踏上月球的阿姆斯特朗,说了一句简单的话:“这是个人的一小步,却是人类的一大步。”
Alter聊科技
2024/11/29
2600
AutoGLM的一小步,人机交互进化的一大步
智谱开源AI绘图CogView4,曾经的开源之光回来了。
上周DeepSeek连续5天开源硬核技术,阿里开源万相2.1,Qwen的推理模型推出预览版,但是肯定马上也要开源。
数字生命卡兹克
2025/04/14
1970
智谱开源AI绘图CogView4,曾经的开源之光回来了。
智谱AI:国产全自研大模型商业化落地新解法
放眼当下的科技浪潮,AI大模型无疑是一年多来持续引人注目的焦点。基于大模型的算法推理,30秒即可生成完美可用的Word、PPT文档,工作时长不必再以小时计算;真人对话一般输入简短文字,就能在30秒内得到想要的图画、代码、文本、视频……大模型让科幻小说中的场景,走进了千行百业、千家万户的现实生活。
大数据文摘
2024/03/21
1K0
智谱AI:国产全自研大模型商业化落地新解法
跟大厂拼价格到底!智谱 AI 宣布模型全面降价,刘慈欣、AI 老罗线上“整活儿
“大模型的 Scaling Law 并未失效,AI 技术的增长进入了一个全新的阶段。也就是说大模型技术的创新依旧是突飞猛进的进行时,甚至还有速度越来越快的迹象。”智谱 AI CEO 张鹏在 6 月 5 日的 Open Day 上说道。
深度学习与Python
2024/06/17
2770
跟大厂拼价格到底!智谱 AI 宣布模型全面降价,刘慈欣、AI 老罗线上“整活儿
智谱AI发布AutoGLM 2.0 - 首个为手机而生的通用Agent。
想一想,AutoGLM1.0的版本,距离我第一次首发写他们,已经过去快10个月了。
数字生命卡兹克
2025/09/04
1680
智谱AI发布AutoGLM 2.0 - 首个为手机而生的通用Agent。
【AGI-Eval行业动态 NO.7】一文读懂Agent,或是AI下一程主角?
最近一段时间,Agent 可以说是毫无争议的 AI 领域顶流话题,在搜索平台随便输入 Agent,满眼都是 “爆火”“刷屏”“重磅” 这样的字眼。2025年初以来,从阿里发布的 Qwen-Agent 框架,到OpenAI 发布的 AI 智能体 Operator ,再到 Manus 的出圈,无一不让人感受到 Agent 发展的迅猛势头。
AGI-Eval评测社区
2025/04/01
2660
【AGI-Eval行业动态 NO.7】一文读懂Agent,或是AI下一程主角?
用行动回应“实体清单”,智谱发布了一系列新模型
1月15日晚间,美国商务部工业和安全局(BIS)修订了《出口管制条例》(EAR),以安全为由在实体清单中分两批增加了25个中国实体。
Alter聊科技
2025/01/16
2180
用行动回应“实体清单”,智谱发布了一系列新模型
智谱AI悄悄发布AutoGLM,这一次,贾维斯真的要成现实了。
他们发了一个AGI进程图,最好玩的还是用了《银河系漫游指南》里面那个终极答案42当了一个梗,而这个AGI进程图其实就是对标的人脑,而AutoGLM,就是AI,使用工具的能力。
数字生命卡兹克
2025/04/14
1360
智谱AI悄悄发布AutoGLM,这一次,贾维斯真的要成现实了。
推荐阅读
第一个免费可用的智能Agent产品全量上线,中国公司智谱打造,推理模型比肩R1
3670
比 R1 快 8 倍、价格仅 3%,智谱新推理模型来袭,能让免费智能体自己赚钱!张鹏:Agent 也有 Scaling Law
2020
AutoGLM沉思:像人一样的深度思考+动手执行,让复杂问题迎刃而解,而且全免费
6100
智谱 GLM 新成员开源:高性能、推理快,体验入口“z.ai”免费开放
4620
智谱发布AutoGLM沉思版,国产DeepResearch来了,人人皆免费。
8930
考研数学得126分、还能编写小游戏,智谱首个推理模型来了,人人免费用
1880
又一AI利器!智谱发布全新推理大模型,速度快8倍,价格比DeepSeek-R1更低~
1960
AI现场发了2万红包,打开了大模型Act时代
1480
智谱Agent抢跑OpenAI,GLM-PC一句话搞定一切!网友:有AGI那味了
1520
智谱AI全新发布Agent家族,用AI操控一切不再是梦了。
1540
智谱AI深夜上线全新Agent GLM-PC,再见仍是巅峰。
1480
智谱AI推出GLM-4,性能逼近ChatGPT-4
8821
AutoGLM的一小步,人机交互进化的一大步
2600
智谱开源AI绘图CogView4,曾经的开源之光回来了。
1970
智谱AI:国产全自研大模型商业化落地新解法
1K0
跟大厂拼价格到底!智谱 AI 宣布模型全面降价,刘慈欣、AI 老罗线上“整活儿
2770
智谱AI发布AutoGLM 2.0 - 首个为手机而生的通用Agent。
1680
【AGI-Eval行业动态 NO.7】一文读懂Agent,或是AI下一程主角?
2660
用行动回应“实体清单”,智谱发布了一系列新模型
2180
智谱AI悄悄发布AutoGLM,这一次,贾维斯真的要成现实了。
1360
相关推荐
第一个免费可用的智能Agent产品全量上线,中国公司智谱打造,推理模型比肩R1
更多 >
LV.0
这个人很懒,什么都没有留下~
目录
  • Java Thread 实现/创建方式
  • Java ThreadPool 线程池有哪些
  • Java Thread LifeCycle 线程的生命周期
  • Java Thread 线程终止的方式
  • Java Thread 中 start, run, sleep, wait 分别是什么
  • Java 后台线程是什么
  • Java 线程的基本方法
  • JAVA 线程的上下文切换 (Context Switch)
  • JAVA 线程上下文切换原因
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档