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

如何在Java中进行多线程编程

在Java中进行多线程编程有多种方式,最常用的包括继承Thread类、实现Runnable接口、实现Callable接口,以及使用线程池等。以下是具体介绍和代码示例:

1. 继承Thread类

通过继承Thread类并重写run()方法来定义线程执行逻辑,然后调用start()方法启动线程。

// 继承Thread类
class MyThread extends Thread {@Overridepublic void run() {for (int i = 0; i < 5; i++) {System.out.println("线程" + Thread.currentThread().getId() + ": " + i);try {Thread.sleep(100); // 休眠100毫秒,模拟任务耗时} catch (InterruptedException e) {e.printStackTrace();}}}
}public class ThreadExample {public static void main(String[] args) {// 创建并启动线程MyThread thread1 = new MyThread();MyThread thread2 = new MyThread();thread1.start(); // 启动线程(调用run()方法)thread2.start();}
}
 
 

2. 实现Runnable接口

实现Runnable接口的run()方法,将任务逻辑与线程分离,更灵活(可避免单继承限制)。

// 实现Runnable接口
class MyRunnable implements Runnable {@Overridepublic void run() {for (int i = 0; i < 5; i++) {System.out.println("线程" + Thread.currentThread().getId() + ": " + i);try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}}}
}public class RunnableExample {public static void main(String[] args) {// 创建任务实例MyRunnable task = new MyRunnable();// 通过Thread包装任务并启动Thread thread1 = new Thread(task);Thread thread2 = new Thread(task);thread1.start();thread2.start();}
}
 
 

3. 实现Callable接口(带返回值)

Callable接口与Runnable类似,但call()方法可以返回结果并抛出异常,通常配合Future使用。

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;// 实现Callable接口(泛型指定返回值类型)
class MyCallable implements Callable<Integer> {private int taskId;public MyCallable(int taskId) {this.taskId = taskId;}@Overridepublic Integer call() throws Exception {int sum = 0;for (int i = 0; i <= 10; i++) {sum += i;Thread.sleep(50);}System.out.println("任务" + taskId + "执行完毕,结果为:" + sum);return sum; // 返回计算结果}
}public class CallableExample {public static void main(String[] args) throws ExecutionException, InterruptedException {// 创建Callable任务MyCallable task1 = new MyCallable(1);MyCallable task2 = new MyCallable(2);// 用FutureTask包装Callable(可获取结果)FutureTask<Integer> future1 = new FutureTask<>(task1);FutureTask<Integer> future2 = new FutureTask<>(task2);// 启动线程new Thread(future1).start();new Thread(future2).start();// 获取任务结果(会阻塞直到任务完成)int result1 = future1.get();int result2 = future2.get();System.out.println("主线程获取结果:" + result1 + "," + result2);}
}
 
 

4. 使用线程池(推荐)

频繁创建销毁线程会消耗资源,线程池可以复用线程,提高效率。Java通过ExecutorsThreadPoolExecutor创建线程池。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;public class ThreadPoolExample {public static void main(String[] args) {// 创建固定大小的线程池(3个线程)ExecutorService executor = Executors.newFixedThreadPool(3);// 提交5个任务到线程池for (int i = 0; i < 5; i++) {final int taskId = i;executor.submit(() -> {// 使用Lambda表达式简化RunnableSystem.out.println("任务" + taskId + "由线程" + Thread.currentThread().getId() + "执行");try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}});}// 关闭线程池(不再接受新任务,等待现有任务完成)executor.shutdown();}
}
 
 

核心概念补充

  • 线程状态:新建(New)→ 就绪(Runnable)→ 运行(Running)→ 阻塞(Blocked/Waiting/Timed Waiting)→ 终止(Terminated)。
  • 线程同步:多线程共享资源时需避免竞争,可使用synchronized关键字、Lock接口等实现同步。
  • 线程通信:通过wait()notify()notifyAll()等方法实现线程间协作。

线程池是实际开发中推荐的方式,因为它能更好地管理线程资源,避免频繁创建线程的开销。

http://www.gsyq.cn/news/24469.html

相关文章:

  • 零售行业绩效流程推行难点及 Tita 目标绩效一体化管理方案
  • 《探索C语言中数组的奥秘(下)》 - 教程
  • [转]学习指南 - PL-600:Microsoft Power Platform 解决方案架构师
  • Vue中keep-alive实现原理解析
  • 深入学习Spring Boot框架
  • java语言程序设计类与对象课后作业 - 20243867孙堃2405
  • java流程控制。
  • 2025年扑灭司林厂家推荐排行榜,高效环保扑灭司林,专业生产与市场口碑深度解析!
  • 3 分钟搞懂 Java 中 this 关键字的用法
  • 折腾笔记[32]-windows部署vscode-server及使用命令行编译c#.net工程
  • 2025润滑油厂家推荐:三特石化全合成长效发动机油,品质卓越!
  • Java 类与对象实践:从代码验证到四则运算开发
  • 2025手持光谱仪厂家推荐:一诺机电精准分析,便携高效检测首选!
  • DP优化:四边形不等式、决策单调性与凸性
  • WPS中Mathtype插件消失不见解决方法
  • 2025年塑料托盘厂家推荐排行榜,网格川字/九脚/田字/双面塑料托盘,平板/吹塑/注塑/焊接/印刷/组装款/高矮脚/反川字/立体库托盘公司精选!
  • 物理感知 RTL 合成
  • 在线p图(PhotoShop网页版)加滤镜,3步搞定唯美照片
  • 实用指南:85-dify案例分享-不用等 OpenAI 邀请,Dify+Sora2工作流实测:写实动漫视频随手做,插件+教程全送
  • uml九大图 - 作业----
  • GapBuffer高效标记管理算法
  • 7.switch语句的简单应用
  • 在AI技术唾手可得的时代,挖掘电池管理工具的新需求成为关键
  • 计算语言学家在科技行业的职业发展指南
  • 新奇特:神经网络的集团作战思维,权重共享层的智慧 - 指南
  • 详细介绍:JVM 性能诊断
  • wqs 二分(凸完全单调性)
  • 2025滑触线优质厂家推荐宸澳电气,安全防爆性能卓越!
  • 2025定型机厂家推荐:鑫源恒进节能高效,智能排风引领行业新趋势!
  • LLM分词器