创建线程的2种方式
线程创建的2种方式
1. 继承Thread类
public class FactorialThreadTester {
public static void main(String[] args) {
System.out.println("main thread starts");
FactorialThread thread = new FactorialThread(10);
thread.start();
System.out.println("main thread ends");
}
}
class FactorialThread extends Thread {
private int num;
public FactorialThead(int num) {
this.num = num;
}
public void run() {
int i = num;
int result = 1;
System.out.println("new thread started");
while(i > 0) {
result = result * i;
i = i - 1;
}
System.out.println("The factorial of " + num + "is " + result);
System.out.println("new thread ends");
}
}
2. 实现Runnable接口
https://www.xuetangx.com/learn/THU08091000252/THU08091000252/7754101/video/12732923
-
Runnable接口
只有一个 run()方法
Thread类 实现了 Runnable接口
便于多个线程 共享资源
Java不支持多继承, 如果已经继承了某个基类, 便需要实现 Runnable 接口 来生成 多线程
以实现 Runnable 的对象 为 参数, 建立新的线程
start方法 启动线程, 就会运行 run()方法
2.1. Runnable接口, 实现单一线程
public class FactorialThreadTester {
public static void main(String[] args) {
System.out.println("main thread starts");
FactorialThread t = new FactorialThread(10); // 实现了Runnable的类
new Thread(t).start(); // 运行 FactorialThread 的 run
System.out.println("new thread started, main thread ends");
}
}
class FactorialThread implements Runnable {
private int num;
public FactorialThread(int num) {
this.num = num;
}
public void run() {
int i = num;
int result = 1;
while (i > 0) {
result = result * i;
i = i - 1;
}
System.out.println("The factorial of " + num + "is" + result);
System.out.println("new thread ends");
}
}
2.2. Runnable接口, 实现多个线程
public class ThreadSleepTester {
public static void main(String[] args) {
TestThread thread1 = new TestThread();
TestThread thread2 = new TestThread();
TestThread thread3 = new TestThread();
System.out.println("Starting threads");
new Thread(thread1, "Thread1").start();
new Thread(thread2, "Thread2").start();
new Thread(thread3, "Thread3").start():
System.out.println("Threads started, main ends\n");
}
}
class TestThread implements Runnable {
private int sleepTime;
public TestThread() {
sleepTime = (int) (Math.random() * 6000);
}
public void run() {
try {
System.out.println(Thread.currentThread().getName() + "going to sleep for " + sleepTime);
Thread.sleep(sleepTime);
} catch (InterruptedException exception) {};
System.out.println(Thread.currentThread().getName() + "finished");
}
}
2种线程构造方式的比较
-
使用Runnable接口
可以将 CPU, 代码, 数据 分开, 形成清晰的模型;
还可以从其他类继承
-
直接继承Thread类
编写简单, 直接继承, 重写run方法, 不能再从其他类继承
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律