当前位置: 首页 > 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.lryc.cn/news/593580.html

相关文章:

  • QT窗口(8)-QFileDiag
  • esp32 sd卡
  • Kubernetes常用命令总结
  • MySQL 深度性能优化配置实战指南
  • 单例模式的设计与实现
  • Salesforce 与外部系统实时集成:基于事件驱动的异步集成架构
  • ChatGPT Agent深度解析:告别单纯问答,一个指令搞定复杂任务?
  • (LeetCode 面试经典 150 题) 49. 字母异位词分组 (哈希表)
  • 软件工程:可行性分析的任务及报告
  • picoCTF 2024: [[NoSQL]] Injection - Writeup
  • JAVA中的Collections 类
  • 【数据结构】二叉树初阶详解(一):树与二叉树基础 + 堆结构全解析
  • windows wsl2-05-docker 安装笔记
  • 光盘存储器的组成与分类
  • 从“数字土著”到“数据公民”:K-12数据伦理课程的设计、实施与成效追踪研究
  • Codeforces Round 1037 (Div. 3)(补题)
  • Codeforces Round 1037(Div.3)
  • 搭建比分网服务器怎么选数据不会卡顿?
  • 配置华为交换机接口链路聚合-支持服务器多网卡Bind
  • 数据结构:字符串(Strings)
  • RGB转灰度方法汇总
  • 本地安装部署Unstructured-api
  • Flutter基础(前端教程①③-单例)
  • 优先算法——专题十:哈希表
  • kafka--基础知识点--6--AR、ISR、OSR
  • Django母婴商城项目实践(九)- 商品列表页模块
  • [论文阅读] 软件工程 | 用模糊逻辑“解锁”项目成功:告别非黑即白的评估时代
  • 多进程服务器
  • 千线万网,电路之行——LVS检查的内核逻辑
  • k8s 基本架构