线程基本概念
创始人
2025-05-28 03:22:25
0

进程是资源分配的最小单位,线程是最小调度单位
并发:轮流交替做多件事情
单核cpu下,多线程不能实际提高程序运行效率,只是不同线程轮流使用cpu
同步:需要等待结果返回,才能继续运行后面的代码
异步:不需要等待结果返回,继续运行后面的代码
线程调度机制

new Thread(() -> FileReader.read("xwfdwf")).start();
log.debug("do other things...");
public static void main(String[] args) {// 默认有一个主线程// 创建线程// 1.Thread的匿名子类的对象Thread t = new Thread(){@Overridepublic void run() {log.debug("cwfcwfcwcwccx");System.out.println("cwcw");}};// 启动t.start();log.debug("main=================");System.out.println("main");
}

执行出来的顺序是随机的
在这里插入图片描述
在这里插入图片描述

// 创建线程的方式
Thread s = new Thread(() -> System.out.println("cwcw"));// 返回结果是Integer
FutureTask fu = new FutureTask<>(new Callable() {@Overridepublic Integer call() throws Exception {log.debug("PPPPP===");return 100;}
});
Thread t = new Thread(fu,"t");
t.start();
System.out.println(fu.get()); // 100

给线程分配一个栈内存,线程的栈内存是相互独立的,每个线程有自己独立的栈
方法,栈帧(局部变量表,返回地址)

线程上下文切换:因为以下一些原因导致cpu不再执行当前线程,转而执行另一个线程
线程的cpu时间片用完
垃圾回收
有更高优先级的线程需要运行
线程自己调用了sleep,yield,wait,join,park,synchronized,lock等方法

当上下文切换时,需要由OS保存当前线程的状态,并恢复另一个线程的状态
Java中对应的概念是程序计数器,作用是记住下一条jvm指令的地址,是线程私有的

常用方法

start:启动一个新线程,在新的线程中运行run方法中的代码
start方法只是让线程进入就绪,里面代码不一定立刻运行
每个线程对象只能调用一次start方法,否则会报IllegalThreadStateExceptiont1.interrupt()
// 打断t1线程
// 如果t1线程在sleep,wait会导致t1线程抛出InterruptedException,并清除打断标记
// 如果t1线程在运行,只是会设置打断标记sleep:进入阻塞态,睡眠结束后的线程未必会立即得到执行,变为就绪态
Thread.yield():让线程让出cpu的使用权,进入就绪状态,使cpu调度其他就绪状态的线程
t1.join();主线程陷入阻塞,等待t1线程运行结束
FutureTask fu = new FutureTask<>(() -> {for (int i = 0; i < 100; i++) {System.out.println("p");}return 100;
});
Thread t1 = new Thread(fu);Thread t2 = new Thread(() -> {try {long l = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());t1.join();long r = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());System.out.println("==========等待时间==========" + (r - l));} catch (InterruptedException e) {e.printStackTrace();}
});
t1.start();
t2.start();
t2.interrupt();// t2线程不再等待t1线程,且抛出异常InterruptedException

进程状态

就绪态:一个进程获得了除CPU之外的所有资源
阻塞态:一个进程正在等待某一事件而暂停运行
在这里插入图片描述

线程状态

    /*** A thread can be in only one state at a given point in time.* These states are virtual machine states which do not reflect* any operating system thread states.*/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,/*** 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* {Object.wait}.*/BLOCKED,/*** Thread state for a waiting thread.* A thread is in the waiting state due to calling one of the* following methods:* {Object.wait} with no timeout* {Thread.join} with no timeout* {LockSupport.park}** A thread in the waiting state is waiting for another thread to* perform a particular action.** For example, a thread that has called {Object.wait()}* on an object is waiting for another thread to call* {Object.notify()} or {Object.notifyAll()} on* that object. A thread that has called {Thread.join()}* 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:*Thread.sleep,Object.wait,Thread.join,LockSupport.parkNanos,LockSupport.parkUntil*/TIMED_WAITING,// Thread state for a terminated thread.The thread has completed execution.TERMINATED;}

默认情况下,Java进程需要等待所有线程都运行结束,才会结束
如果有一个守护线程,则只要其他非守护线程运行结束,整个程序就会结束

相关内容

热门资讯

黄金“不灵了”,高端金饰的溢价... 古法黄金到底能不能走出脱离金价波动的独立溢价 作者:赵心怡 2026年开年,国际金价一路狂飙至近56...
朗迅科技由董事长徐振控制46%... 瑞财经 刘治颖 6月24日,杭州朗迅科技股份有限公司(以下简称:朗迅科技)深主板IPO获受理,保荐机...
两部门:2030年可再生能源制... 【两部门:2030年可再生能源制氢规模达到200万吨】财联社6月25日电,国家发展改革委、国家能源局...
原创 警... 大家好,这里是全球脉冲。 6月16日,日本央行宣布加息25个基点,政策利率上调至1%,创下31年来最...
黄金钻石回收怎么选?上海市场常... 近年来黄金价格持续走高,不少上海市民都有变现家中闲置黄金首饰、投资金条的打算。但市面上回收门店数量众...
专访火山引擎谭待:模型好对Ma... 文 | 邓咏仪 编辑 | 张雨忻 火山引擎总裁谭待 来源:火山引擎 过去三年,火山引擎总裁谭待给团...
女董事长深夜被带走,牵出金融旧... *此图由AI生成 作者| 史大郎&猫哥 来源| 是史大郎&大猫财经Pro 大半夜的,一家上市公司董事...
盯盯拍报考港交所上市:出海翻红... 撰稿|贝多 来源|贝多商业&贝多财经 6月22日,盯盯拍(深圳)技术股份有限公司(下称“盯盯拍”)递...
苏州千亿市值上市公司+1! A股“苏州板块”又诞生了一家千亿市值企业。 昨日(6月25日),苏州上市公司永鼎股份股价在昨日涨停的...
芯片股猛拉!600667,一字... 【导读】创业板指一度涨超2%,存储芯片、半导体、电子元器件等方向涨幅居前 中国基金报记者 李智 一起...
分析师:海峡收费与否已不重要 ... 来源:格隆汇APP 格隆汇6月25日|阿曼方面重申,霍尔木兹海峡未来安排不涉及通行费。美国财经网站i...
《内外贸一体化企业评价通则》团... 齐鲁晚报·齐鲁壹点记者 管悦 6月25日,《内外贸一体化企业评价通则》团体标准审查会在济南召开。该标...
提升AI智能体工作流的速度与能... 智能体工作流是一种由AI驱动的软件系统,它通过串联多个模型与外部工具来处理复杂任务,例如分析视频并回...
热搜!又有纸尿裤被曝检出甲酰胺... 来源:市场资讯 (来源:北京商报) 网友:“囤了200多包”。 近日,多个婴幼儿纸尿裤品牌“被检出...
埃森哲内部录音曝光:企业AI使... IT之家 6 月 26 日消息,科技媒体 404Media 昨日(6 月 25 日)发布博文,披露了...
FIBA期待杨瀚森表现 最新实... 北京时间6月25日消息,FIBA国际篮联公布了最新一期世界杯预选赛亚太区球队实力榜,中国男篮排在澳大...
收评:创业板指放量反弹涨2.8... 市场冲高回落后,再度震荡拉升。黄白线分化明显,权重股走势较强。量能明显放大,沪深两市成交额3.59万...
巨头财报引爆A股存储芯片板块,... 当地时间6月24日美股盘后, 美光科技(MU.US)公布截至5月31日的2026财年第三财季财报,业...
银行、消金公司助贷余额增速不得... 近日,中国证券报记者从多位业内人士处独家获悉,5月以来,多地金融监管部门对部分中小银行、消金公司下达...