线程基本概念
创始人
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进程需要等待所有线程都运行结束,才会结束
如果有一个守护线程,则只要其他非守护线程运行结束,整个程序就会结束

相关内容

热门资讯

黄金闪崩9%!白银跌27%?别... 伦敦金现一天跌9.45%,A股黄金概念股大面积跌停;白银更是单日暴跌26.77%。一夜之间,曾经高歌...
周末这两大重要消息,对2月A股... 刚过去的交易周(1月26日至30日),A股整体呈现放量震荡格局,日均成交额超3万亿元。在大资金持续净...
新任美联储主席提名人选,为什么... 新任美联储主席提名人选终于揭晓。 据新华社报道,美国总统特朗普30日提名美联储前理事凯文·沃什为下任...
上游观察・两会|“十五五”开新... 2月1日上午,2026重庆两会圆满落幕。 回望“十四五”,新重庆交出亮眼答卷——成为中西部地区首个经...
雷军确认一月锁单未交付小米YU... IT之家 2 月 1 日消息,小米今日公布小米 YU7 全新「7 年低息」方案,对于“一月锁单未交付...
项链小红书获客封神攻略!家装人... 做项链饰品的宝子是不是都有同款崩溃:拍100张精修图、写半天文案,笔记互动却个位数;投流花了钱,到店...
SpaceX申请部署100万颗... 大象新闻2026-02-01 10:39:51 据美国《个人电脑杂志》网站1月31日报道,马斯克旗下...
美股点金丨避险情绪升级,美股2... 美股本周尾盘走低,不过三大股指仍以亮眼表现收官1月。下周市场将迎来月度就业报告,外界对货币政策预期可...
肿瘤患者饮食“三不要三要”,吃... 一、饮食“三不要”,避开抗癌饮食坑 1. 不要轻信“饿死癌细胞”:癌细胞会优先抢夺身体营养,盲目节...
宜家在中国败给了谁? 作者 | 会写字的机器猫 来源|新消费智库 图片 | AI生成 新消费导读 上海宝山宜家商场,那个...
证监会拟扩大战略投资者类型并明... 记者1月30日从中国证监会获悉,为贯彻落实《关于推动中长期资金入市的指导意见》和《关于推动中长期资金...
突然大跌!加密货币市值一夜蒸发... 2月1日凌晨,比特币一度跌至75719美元/枚,跌至2025年4月以来的最低水平。截至发稿,比特币回...
刚刚,大跳水!超42万人爆仓!... 来源:券商中国 加密货币,遭遇抛售潮! 凯文·沃什被提名为下一任美联储主席所产生的后续效应,正持续波...
做好银行网点“加减法” 国家金融监督管理总局网站披露的信息显示,2025年共有约1.1万家银行业金融机构的线下网点获准退出,...
金价暴跌引热议,网友:商场门口... 来源:中国基金报 随着国际金价急速下跌,国内首饰金价也迎来大幅回调。 1月31日,老庙报1546元/...
内蒙古一银行员工将储户220万... 内蒙古一银行员工将储户220万元存款转走并挥霍,银行称员工已离岗不愿承担赔偿 1月31日,有媒体报...
老年医学科进修轶事|老年医学如... 和年苑,北京协和医院老年医学科公众号,传递老年医学的价值和声音 在这里,了解当代老年医学 Autum...
和讯投顾余兴栋:周五杀跌,下周... 周五大盘大幅度的杀跌又探底回升,收出一根长长的下影线,不少的朋友又在问我,那这根k线是不是就意味着调...
【数智周报】马化腾评豆包手机;... 【数智周报将整合本周最重要的企业级服务、云计算、大数据领域的前沿趋势、重磅政策及行研报告。】 观点马...