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/11/1 21:02:18 阅读更多 →
线上评选系统选购指南|人人微投票、365评选实测对比

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

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

2026/11/1 21:02:19 阅读更多 →
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/11/1 19:46:43 阅读更多 →

最新新闻

Electron桌面应用开发实战:从环境搭建到打包发布全流程

Electron桌面应用开发实战:从环境搭建到打包发布全流程

做前端这些年,我大部分时间都在跟浏览器标签页打交道,直到第一次把桌面应用跑起来,才发现原来自己一直被限制在地址栏和刷新按钮围起来的框框里。Electron这个词,最开始是在某段时间频繁出现在同事的讨论里,一个用HTML…

2026/11/2 0:25:10 阅读更多 →
滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

简介:亚太天能T109滑盖智能锁产品说明书是一份PDF格式的官方技术文档,主要面向智能锁安装人员、终端用户及售后维护者,帮助快速掌握产品安装、配置与常见故障处理。全包仅1个PDF文件,大小4.37MB,内容结构清晰&#xff…

2026/11/1 10:36:53 阅读更多 →
PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

上个月我在调试一台高速AGV的驱动系统,整车要求空载跑到8m/s,电机转速已经拉到额定点,驱动器的输出电压也顶到了母线电压极限附近。再往上踩速度指令,转速纹丝不动,三相电流反而开始震荡。那会儿我的第一反应就是&…

2026/11/1 10:36:51 阅读更多 →
C++核心知识点:从内存管理到STL的实战指南

C++核心知识点:从内存管理到STL的实战指南

C 这门语言我前前后后折腾了十几年,用它写过嵌入式驱动、做过游戏服务端,也搭过基础组件库。每次看到新人一头扎进"C 核心知识点"这个搜索词,我其实挺感慨的——这门语言的难点从来不是语法多,而是知识点之间的耦合太深…

2026/11/1 1:06:58 阅读更多 →
T109滑盖智能锁怎么装?安装调试与故障排查全攻略

T109滑盖智能锁怎么装?安装调试与故障排查全攻略

简介:亚太天能T109滑盖智能锁产品说明书以PDF格式发布,适合智能锁用户、安装人员与售后维修人员阅读。内容围绕T109系列指纹密码刷卡锁展开,先介绍前面板、后面板、锁体、机械钥匙、电池盒盖等部件名称与功能,再给出完整安装步骤&…

2026/11/1 10:35:11 阅读更多 →
LLM知识降熵:从信息垄断到理解权下放

LLM知识降熵:从信息垄断到理解权下放

你有没有过这种经历:翻开源码注释、论文摘要或者一份专业报告,每个字都认识,连在一起却像天书。想找人聊聊,身边要么没人懂,要么懂的懒得跟你解释。后来我试着把同一段内容丢给一个大语言模型,几秒钟之后&a…

2026/11/1 9:35:41 阅读更多 →

日新闻

周新闻

月新闻