Java 多线程(抢CPU)
哈哈哈什么是多线程可以让程序同时做多件事情。多线程的作用提高效率。多线程的应用场景想让多个事情同时运行。并发多个指令在单个CPU交替执行和并行多个指令在多个CPU交替执行多线程的实现方式1.继承Thread类的方式实现简单扩展性差public class ss { public static void main(String[] args) { //1.自己定义一个类继承Thread //2.重写run方法 //3.创建子类的对象并启动线程 MyThread t1new MyThread(); MyThread t2new MyThread(); t1.setName(1); t2.setName(2); t1.start(); t2.start(); } }public class MyThread extends Thread{ Override public void run(){ for (int i 0; i 100; i) { System.out.println(getName()hello); } } }2.实现Runnable接口的方式进行实现复杂扩展性强public class ss { public static void main(String[] args) { //1.自己定义一个类实现Runnable接口 //2.重写里面的run方法 //3.创建自己的类的对象 //4.创建一个Thread类的对象并开启线程 MyRun mrnew MyRun(); Thread tnew Thread(mr); Thread t2new Thread(mr); t.setName(1); t2.setName(2); t.start(); t2.start(); } }public class MyRun implements Runnable{ Override public void run() { for (int i 0; i 100; i) { Thread tThread.currentThread(); System.out.println(t.getName()hello); } } }3.利用Callable接口和Future接口方式实现可以获取结果import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; public class ss { public static void main(String[] args) throws ExecutionException, InterruptedException { //1.创建一个类MyCallable实现Callable接口 //2.重写call //3.创建MyCallable对象 //4.创建FutureTask的对象 //5.创建Thread类对象并启动 MyCallable mcnew MyCallable(); FutureTaskInteger ftnew FutureTask(mc); Thread t1new Thread(ft); t1.start(); Integer resultft.get(); System.out.println(result); } }import java.util.concurrent.Callable; public class MyCallable implements CallableInteger{ Override public Integer call() throws Exception{ int sum0; for (int i 0; i 100; i) { sumsumi; } return sum; } }多线程的常用成员方法public class ss { public static void main(String[] args) throws InterruptedException { //getName MyThread mtnew MyThread(111); MyThread t2new MyThread(); mt.start(); t2.start(); //setName //.... //currentThread Thread tThread.currentThread(); System.out.println(t.getName()); //sleep(long time)毫秒 睡眠时间 System.out.println(11111); Thread.sleep(5000); System.out.println(22222); } }public class MyThread extends Thread{ public MyThread() { } public MyThread(String name) { super(name); } Override public void run() { for (int i 0; i 100; i) { try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println(getName()i); } } }线程的优先级public class ss { public static void main(String[] args) throws InterruptedException { MyRunnable mrnew MyRunnable(); Thread t1new Thread(mr,1); Thread t2new Thread(mr,2); System.out.println(t1.getPriority());//默认优先级5 System.out.println(t2.getPriority());//默认优先级5//最小1//最大10 t1.setPriority(1); t2.setPriority(10); t1.start(); t2.start(); } }public class MyRunnable implements Runnable{ Override public void run() { for (int i 0; i 100; i) { System.out.println(Thread.currentThread().getName()i); } } }守护线程起码有2个线程public class ss { public static void main(String[] args) throws InterruptedException { MyThread t1new MyThread(); MyThread2 t2new MyThread2(); t1.setName(1); t2.setName(2); t2.setDaemon(true); t1.start(); t2.start(); } }public class MyThread extends Thread{ Override public void run() { for (int i 0; i 10; i) { System.out.println(getName()i); } } }public class MyThread2 extends Thread{ Override public void run() { for (int i 0; i 10; i) { System.out.println(getName()i); } } }礼让线程public class ss { public static void main(String[] args) throws InterruptedException { MyThread2 t1new MyThread2(); MyThread2 t2new MyThread2(); t1.setName(1); t2.setName(2); t1.start(); t2.start(); } }public class MyThread2 extends Thread{ Override public void run() { for (int i 0; i 100; i) { System.out.println(getName()i); Thread.yield();//礼让一下再重新抢夺CPU的执行权 } } }插入线程/插队线程public class ss { public static void main(String[] args) throws InterruptedException { MyThread t1new MyThread(); t1.setName(1); t1.start(); t1.join();//把t线程插入到当前线程main之前 for (int i 0; i 10; i) { System.out.println(maini); } } }public class MyThread extends Thread{ Override public void run() { for (int i 0; i 100; i) { System.out.println(getName()i); } } }线程的生命周期一个线程从创建到结束。线程的安全问题下面这个代码存在问题public class ss { public static void main(String[] args) throws InterruptedException { MyThread t1new MyThread(); MyThread t2new MyThread(); MyThread t3new MyThread(); t1.setName(窗口1); t2.setName(窗口2); t3.setName(窗口3); t1.start(); t2.start(); t3.start(); } }public class MyThread extends Thread{ static int ticket0;//这个类所有对象共享ticket数据加了static Override public void run() { while (true){ if(ticket100){ try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } ticket; System.out.println(getName()正在卖第ticket张票); }else break; } } }同步代码块可以解决问题public class ss { public static void main(String[] args) throws InterruptedException { MyThread t1new MyThread(); MyThread t2new MyThread(); MyThread t3new MyThread(); t1.setName(窗口1); t2.setName(窗口2); t3.setName(窗口3); t1.start(); t2.start(); t3.start(); } }public class MyThread extends Thread{ static int ticket0;//这个类所有对象共享ticket数据加了static static Object objnew Object(); Override public void run() { while (true){ synchronized (obj){ if(ticket100){ try { Thread.sleep(100); } catch (InterruptedException e) { throw new RuntimeException(e); } ticket; System.out.println(getName()正在卖第ticket张票); }else break; } } } }同步方法就是把synchronized关键字加到方法上public class ss { public static void main(String[] args) throws InterruptedException { MyRunnable mrnew MyRunnable(); Thread t1new Thread(mr); Thread t2new Thread(mr); Thread t3new Thread(mr); t1.setName(窗口1); t2.setName(窗口2); t3.setName(窗口3); t1.start(); t2.start(); t3.start(); } }public class MyRunnable implements Runnable{ int ticket0; Override public void run() { while (true){ if (method()) break; } } private synchronized boolean method() { if(ticket100){ return true; }else{ try { Thread.sleep(10); } catch (InterruptedException e) { throw new RuntimeException(e); } ticket; System.out.println(Thread.currentThread().getName()在卖第ticket张票); } return false; } }lock锁死锁等待唤醒机制1.消费者2.生产者public class Test { public static void main(String[] args) { Cook cnew Cook(); Foodie fnew Foodie(); // c.setName(厨师); // f.setName(吃货); c.start(); f.start(); } }public class Foodie extends Thread{ Override public void run() { while (true){ synchronized (Desk.lock){ if(Desk.count0){ break; }else{ if(Desk.foodFlag0){ try { Desk.lock.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } else{ Desk.count--; System.out.println(吃货还能吃Desk.count碗); Desk.lock.notifyAll(); Desk.foodFlag0; } } } } } }public class Cook extends Thread{ Override public void run() { while (true){ synchronized (Desk.lock){ if(Desk.count0){ break; }else { if (Desk.foodFlag1){ try { Desk.lock.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } }else { System.out.println(厨师做了一碗面条); Desk.foodFlag1; Desk.lock.notifyAll(); } } } } } }public class Desk { public static int foodFlag0;//桌上是否有食物 public static int count10; public static Object locknew Object(); }利用阻塞队列方式实现import java.util.concurrent.ArrayBlockingQueue; public class Test { public static void main(String[] args) { ArrayBlockingQueueString queuenew ArrayBlockingQueue(1); Cook cnew Cook(queue); Foodie fnew Foodie(queue); c.start(); f.start(); } }import java.util.concurrent.ArrayBlockingQueue; public class Foodie extends Thread{ ArrayBlockingQueueString queue; public Foodie(ArrayBlockingQueueStringqueue){ this.queuequeue; } Override public void run() { while (true){ try { String foodqueue.take(); System.out.println(food); } catch (InterruptedException e) { throw new RuntimeException(e); } } } }public class Desk { public static int foodFlag0;//桌上是否有食物 public static int count10; public static Object locknew Object(); }import java.util.concurrent.ArrayBlockingQueue; public class Cook extends Thread{ ArrayBlockingQueueString queue; public Cook(ArrayBlockingQueueStringqueue){ this.queuequeue; } Override public void run() { while (true){ try { queue.put(面条); System.out.println(厨师做了一碗面条); } catch (InterruptedException e) { throw new RuntimeException(e); } } } }多线程的6种状态线程池1.创建线程池2.提交任务3.所有任务全部执行完毕关闭线程池import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class n { public static void main(String[] args) { // 1.获取线程池对象 // ExecutorService pool1Executors.newCachedThreadPool();//无上限 ExecutorService pool1Executors.newFixedThreadPool(3);//有上限 // 2.提交任务 pool1.submit(new MyRunnable()); pool1.submit(new MyRunnable()); pool1.submit(new MyRunnable()); pool1.submit(new MyRunnable()); // 3.销毁线程池 pool1.shutdown(); } }public class MyRunnable implements Runnable{ Override public void run() { for (int i 0; i 100; i) { System.out.println(Thread.currentThread().getName()---i); } } }自定义线程池回头再看最大并行数4核8线程最大并行数8public class sa { public static void main(String[] args) { int countRuntime.getRuntime().availableProcessors(); System.out.println(count); } }线程池多大合适CPU密集型运算 最大并行数1I/O密集型运算 最大并行数*期望CPU利用率*总时间(CPU计算时间等待时间)/CPU计算时间多线程的额外扩展内容回头再看

相关新闻

浏览器扩展开发者必知:ExtensionPay.js错误处理与调试方法

浏览器扩展开发者必知:ExtensionPay.js错误处理与调试方法

浏览器扩展开发者必知:ExtensionPay.js错误处理与调试方法 【免费下载链接】ExtPay The JavaScript library for ExtensionPay.com — payments for your browser extensions, no server needed. 项目地址: https://gitcode.com/gh_mirrors/ex/ExtPay Extens…

2026/8/5 21:04:17 阅读更多 →
线上评选系统选购指南|人人微投票、365评选实测对比

线上评选系统选购指南|人人微投票、365评选实测对比

线上投票活动选型不当,容易出现中途功能收费、刷票无法管控、数据无法导出存档等问题。市面多数标注“免费”的投票工具存在隐形限制,如何根据活动规模、评选严谨度选择合适平台,是主办方的核心需求。在选择投票工具前,可通过四个…

2026/8/6 23:01:16 阅读更多 →
WPF现代化UI开发架构革命:iNKORE.UI.WPF.Modern的设计范式与技术实现

WPF现代化UI开发架构革命:iNKORE.UI.WPF.Modern的设计范式与技术实现

WPF现代化UI开发架构革命:iNKORE.UI.WPF.Modern的设计范式与技术实现 【免费下载链接】UI.WPF.Modern Modern (Fluent 2) styles and controls for your WPF applications 项目地址: https://gitcode.com/gh_mirrors/ui/UI.WPF.Modern 在桌面应用程序开发领域…

2026/8/5 21:03:17 阅读更多 →

最新新闻

远心镜头原理与应用:精密测量的光学解决方案

远心镜头原理与应用:精密测量的光学解决方案

1. 远心镜头基础认知:为什么它如此特别?第一次接触远心镜头是在2015年的一次半导体检测设备改造项目中。当时产线上的传统镜头在测量0.2mm以下的芯片引脚时,总是出现5μm的测量波动,而改用远心镜头后直接降到了1μm以内。这种神奇…

2026/8/6 23:00:51 阅读更多 →
科研经费这么紧,为什么有些实验室每年能省下一台设备的钱?

科研经费这么紧,为什么有些实验室每年能省下一台设备的钱?

实验室经费紧张,是每个课题组负责人都要面对的现实。开源难,节流就成了必修课。但节流不是“买便宜的”,而是“买对的”——在保证质量的前提下,把采购成本和管理成本降到最低。传统采购模式下,钱是怎么“漏”掉的&…

2026/8/6 23:00:51 阅读更多 →
Kimi k3 “deepseek 2.0时刻”

Kimi k3 “deepseek 2.0时刻”

Kimi K3‌是月之暗面公司于‌2026 年 7 月 17 日‌正式发布的新一代 AI 大模型,拥有‌2.8 万亿参数‌和‌100 万 token 上下文窗口‌,是全球参数规模最大的开源模型,已于‌2026 年 7 月 27 日晚‌正式开源模型权重与技术报告。k3的编程能力‌…

2026/8/6 23:00:51 阅读更多 →
解决欧路词典与WD Discovery冲突的DLL兼容性问题

解决欧路词典与WD Discovery冲突的DLL兼容性问题

1. 问题现象与初步诊断最近遇到一个挺有意思的故障案例:用户运行欧路词典时突然弹出"FuncServer_WDC_x86.exe 应用程序错误"的提示框,导致软件无法正常使用。这个错误提示看起来像是某个后台服务进程崩溃了,但实际排查后发现解决方…

2026/8/6 23:00:51 阅读更多 →
5分钟上手alpaca-backtrader-api:从安装到第一个回测策略的快速教程

5分钟上手alpaca-backtrader-api:从安装到第一个回测策略的快速教程

5分钟上手alpaca-backtrader-api:从安装到第一个回测策略的快速教程 【免费下载链接】alpaca-backtrader-api Alpaca Trading API integrated with backtrader 项目地址: https://gitcode.com/gh_mirrors/al/alpaca-backtrader-api alpaca-backtrader-api是…

2026/8/6 23:00:51 阅读更多 →
UIScrollView-Examples实战:10分钟实现完美的委托方法(Delegate)处理

UIScrollView-Examples实战:10分钟实现完美的委托方法(Delegate)处理

UIScrollView-Examples实战:10分钟实现完美的委托方法(Delegate)处理 【免费下载链接】UIScrollView-Examples UIScrollView examples for blog post 项目地址: https://gitcode.com/gh_mirrors/ui/UIScrollView-Examples UIScrollView-Examples是一个专注于…

2026/8/6 22:59:51 阅读更多 →

日新闻

深入解析LimboAI C++内核:架构设计与性能优化实战

深入解析LimboAI C++内核:架构设计与性能优化实战

1. 项目概述:为什么我们需要深入LimboAI的C内核?如果你是一名使用Godot引擎的游戏开发者,尤其是对AI行为逻辑有较高要求的项目,那么LimboAI这个名字你大概率不会陌生。它作为Godot 4生态中一个备受瞩目的行为树与状态机插件&#…

2026/8/6 0:00:06 阅读更多 →
Unity 2D游戏敌人AI系统:基于PlayMaker状态机与2D Toolkit的实战开发

Unity 2D游戏敌人AI系统:基于PlayMaker状态机与2D Toolkit的实战开发

1. 项目概述与核心思路大家好,我是老张,一个在游戏开发一线摸爬滚打了十多年的老码农。今天咱们接着聊《空洞骑士》风格2D动作游戏的Demo制作。上一期我们搭好了基础框架,处理了角色移动和碰撞,这一期,我们要让游戏世界…

2026/8/6 0:00:06 阅读更多 →
被动防火门市场前景发展趋势

被动防火门市场前景发展趋势

被动防火门依靠材质结构、密闭构造阻隔烟火蔓延,无需电控启动,是建筑被动消防系统核心构件,行业依托新规管控、城市更新、工业安全升级迎来稳定扩容,整体朝着合规化、专项化、低碳化、智能化方向发展。现阶段 GB12955‑2024 新版国…

2026/8/6 0:00:06 阅读更多 →

周新闻

最大流算法详解:从水管网络到Ford-Fulkerson与Dinic实战

最大流算法详解:从水管网络到Ford-Fulkerson与Dinic实战

1. 从水管网络到最大流:一个核心问题的诞生想象一下,你是一个城市供水系统的总工程师。你的城市有多个水源(水库),需要通过一个复杂的地下管道网络,将水输送到各个居民区。每条管道都有其最大通水能力&…

2026/8/6 22:02:27 阅读更多 →
基于Springboot的企业门户网站(源码+LW+调试文档+讲解)

基于Springboot的企业门户网站(源码+LW+调试文档+讲解)

温馨提示:本人主页置顶文章(点我)开头有 CSDN 平台官方提供的学长联系方式的名片! 温馨提示:本人主页置顶文章(点我)开头有 CSDN 平台官方提供的学长联系方式的名片! 温馨提示:本人主页置顶文章(点我)开头有 CSDN 平台…

2026/8/6 22:02:27 阅读更多 →
MATLAB xcorr函数详解:从互相关原理到四大实战应用

MATLAB xcorr函数详解:从互相关原理到四大实战应用

1. 从一次信号“找茬”说起:为什么我们需要互相关几年前,我在处理一组声学传感器数据时遇到了一个棘手的问题。我有两个麦克风记录了一段相同的音频信号,理论上它们接收到的声音波形应该非常相似,只是由于麦克风位置不同&#xff…

2026/8/6 22:02:27 阅读更多 →

月新闻

免费解锁百度网盘SVIP加速:macOS用户必备的下载提速终极指南

免费解锁百度网盘SVIP加速:macOS用户必备的下载提速终极指南

免费解锁百度网盘SVIP加速:macOS用户必备的下载提速终极指南 【免费下载链接】BaiduNetdiskPlugin-macOS For macOS.百度网盘 破解SVIP、下载速度限制~ 项目地址: https://gitcode.com/gh_mirrors/ba/BaiduNetdiskPlugin-macOS 还在为百度网盘macOS版的龟速下…

2026/8/5 23:28:39 阅读更多 →
终极ncmdump指南:3分钟实现网易云NCM音乐解密与格式转换

终极ncmdump指南:3分钟实现网易云NCM音乐解密与格式转换

终极ncmdump指南:3分钟实现网易云NCM音乐解密与格式转换 【免费下载链接】ncmdump 项目地址: https://gitcode.com/gh_mirrors/ncmd/ncmdump 还在为网易云音乐下载的NCM格式文件无法在其他播放器播放而烦恼吗?ncmdump解密工具帮你轻松解决这个困…

2026/8/6 22:02:28 阅读更多 →
HarmonyOS 应用开发《掌上英语》第81篇: 智能体卡片:为英语学习 App 打造桌面级学习助手

HarmonyOS 应用开发《掌上英语》第81篇: 智能体卡片:为英语学习 App 打造桌面级学习助手

AgentCard 智能体卡片:为英语学习 App 打造桌面级学习助手适用平台:HarmonyOS 7.0 (API 26 Beta)一、引言 HarmonyOS 7.0(API 26 Beta)新增了 AgentCard 智能体卡片能力,这是继 HMAF(鸿蒙智能体框架&#x…

2026/8/5 23:46:51 阅读更多 →