当前位置: 首页 > news >正文

多线程 示例

继承Thread类实现多线程

package com.example.demo1;// 方式一:继承Thread类
class MyThread extends Thread {// 重写run()方法(线程执行体)@Overridepublic void run() {// 获取当前线程名称(通过父类方法)System.out.println("当前线程名(继承Thread): " + getName()); // 线程休眠示例(暂停200ms)try {Thread.sleep(200); } catch (InterruptedException e) {e.printStackTrace();}// 输出线程优先级System.out.println(getName() + " 优先级: " + getPriority()); }
}public class ThreadDemo {public static void main(String[] args) {// 创建线程对象MyThread t1 = new MyThread();MyThread t2 = new MyThread();// 设置线程名称(方式1:通过setName)t1.setName("线程A");// 设置线程名称(方式2:通过构造方法,需在MyThread中添加带参构造)t2 = new MyThread() {{ setName("线程B"); }}; // 设置优先级(范围1-10,默认5)t1.setPriority(Thread.MAX_PRIORITY); // 10t2.setPriority(Thread.MIN_PRIORITY); // 1// 启动线程(JVM会调用run())t1.start(); t2.start(); // 主线程输出当前线程信息System.out.println("主线程名: " + Thread.currentThread().getName()); }
}

实现Runnable接口

package com.example.demo1;// 方式二:实现Runnable接口(推荐,避免单继承限制)
class MyRunnable implements Runnable {@Overridepublic void run() {// 通过Thread.currentThread()获取当前线程对象Thread current = Thread.currentThread();System.out.println("当前线程名(Runnable): " + current.getName());// 线程休眠示例(暂停300ms)try {Thread.sleep(300);} catch (InterruptedException e) {e.printStackTrace();}}
}public class RunnableDemo {public static void main(String[] args) {// 创建Runnable任务MyRunnable task = new MyRunnable();// 使用Thread(Runnable target)构造线程Thread t1 = new Thread(task);// 使用Thread(Runnable target, String name)构造带名称的线程Thread t2 = new Thread(task, "线程C"); t1.start();t2.start();}
}

实现Callable接口

package com.example.demo1;import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;// 方式三:实现Callable接口(可获取返回值)
class MyCallable implements Callable<String> {@Overridepublic String call() throws Exception { // 可声明异常Thread.sleep(100); // 模拟耗时操作return Thread.currentThread().getName() + " 执行完成"; }
}public class CallableDemo {public static void main(String[] args) throws Exception {// 创建Callable任务MyCallable callable = new MyCallable();// 用FutureTask包装Callable(桥接Callable和Thread)FutureTask<String> futureTask = new FutureTask<>(callable);// 启动线程(FutureTask本身是Runnable)new Thread(futureTask, "线程D").start(); // 获取结果(阻塞直到完成)String result = futureTask.get(); System.out.println("Callable返回结果: " + result);}
}

守护线程示例

package com.example.demo1;class DaemonTask implements Runnable {@Overridepublic void run() {while (true) {System.out.println("守护线程运行中...");try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}}}
}public class DaemonThreadDemo {public static void main(String[] args) throws InterruptedException {Thread daemonThread = new Thread(new DaemonTask());// 设置为守护线程(必须在start()前调用)daemonThread.setDaemon(true); daemonThread.start();// 主线程运行2秒后结束Thread.sleep(2000);System.out.println("主线程结束,JVM退出");}
}

http://www.xdnf.cn/news/1153279.html

相关文章:

  • leetcode_121 买卖股票的最佳时期
  • AWS Partner: Accreditation (Technical)
  • 轻松上手:从零开始启动第一个 Solana 测试节点
  • 综合实验--eNSP实验
  • TypeScript 泛型详解:从基础到实战应用
  • Linux中添加重定向(Redirection)功能到minishell
  • python网络爬虫之selenium库(二)
  • 【Web APIs】JavaScript 自定义属性操作 ② ( H5 自定义属性 )
  • 图片放大镜案例
  • Patch-wise Structural:一种引入局部统计特性的时序预测损失函数
  • CS231n-2017 Lecture3线性分类器、最优化笔记
  • QT窗口(7)-QColorDiag
  • [spring6: AspectJAdvisorFactory AspectJProxyFactory]-源码解析
  • Linux C 信号操作
  • “外卖大战”正在改变国内“大零售”
  • 图解系统-小林coding笔记
  • 骑行邂逅LV巨轮,VELO维乐Angel Rise坐垫与时尚超适配
  • YOLOv11改进 | RFAConv重塑空间注意力助力性能提升
  • 开关电源和线性电源Multisim电路仿真实验汇总——硬件工程师笔记
  • 使用UV管理FastAPI项目
  • HOT100——动态规划篇Leetcode221. 最大正方形
  • 模型自信度提升:增强输出技巧
  • 纸板制造糊机操作
  • Datawhale AI数据分析 作业
  • 基于朴素贝叶斯的姓名性别预测系统
  • Ubuntu20.04 samba配置
  • 2023年CSP入门级第二轮第四题——旅游巴士
  • 马走日题解
  • Apache Kafka 学习笔记
  • 手撕Spring底层系列之:注解驱动的魔力与实现内幕