Java Thread类
外观
Java Thread类是Java多线程编程的核心类之一,位于java.lang
包中。它允许开发者创建和管理线程,实现并发执行任务的能力。本文将详细介绍Thread类的基本用法、核心方法、生命周期以及实际应用场景。
概述[编辑 | 编辑源代码]
在Java中,线程是程序执行的最小单元。Thread类提供了创建和控制线程的机制,支持以下功能:
- 线程的创建与启动
- 线程状态的监控(如运行、阻塞、终止)
- 线程优先级设置
- 线程同步与协作
创建线程的两种方式[编辑 | 编辑源代码]
Java中创建线程有两种主要方式:
1. 继承Thread类并重写run()
方法。
2. 实现Runnable接口并将实例传递给Thread类的构造函数。
方式1:继承Thread类[编辑 | 编辑源代码]
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread is running: " + Thread.currentThread().getName());
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 启动线程
}
}
输出示例:
Thread is running: Thread-0
start()
方法会调用run()
,并在新线程中执行。
方式2:实现Runnable接口[编辑 | 编辑源代码]
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Runnable is running: " + Thread.currentThread().getName());
}
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
输出示例:
Runnable is running: Thread-0
- 推荐使用此方式,避免单继承限制,且更符合面向对象设计。
Thread类的核心方法[编辑 | 编辑源代码]
以下是Thread类的关键方法:
方法 | 描述 |
---|---|
start() |
启动线程,JVM调用run() 。
|
run() |
线程的实际执行逻辑(需重写或通过Runnable提供)。 |
sleep(long millis) |
使线程暂停指定毫秒数。 |
join() |
等待线程终止。 |
interrupt() |
中断线程。 |
isAlive() |
检查线程是否存活。 |
示例:sleep()与interrupt()[编辑 | 编辑源代码]
public class SleepExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
try {
Thread.sleep(2000);
System.out.println("Awake after sleep");
} catch (InterruptedException e) {
System.out.println("Thread was interrupted!");
}
});
thread.start();
thread.interrupt(); // 中断线程
}
}
输出示例:
Thread was interrupted!
线程的生命周期[编辑 | 编辑源代码]
线程的状态可通过Thread.State
枚举表示:
实际应用案例[编辑 | 编辑源代码]
场景:多线程下载文件[编辑 | 编辑源代码]
public class FileDownloader extends Thread {
private String url;
public FileDownloader(String url) {
this.url = url;
}
@Override
public void run() {
System.out.println("Downloading from " + url + " on " + getName());
// 模拟下载耗时
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Download completed: " + url);
}
public static void main(String[] args) {
new FileDownloader("http://example.com/file1").start();
new FileDownloader("http://example.com/file2").start();
}
}
输出示例:
Downloading from http://example.com/file1 on Thread-0 Downloading from http://example.com/file2 on Thread-1 Download completed: http://example.com/file1 Download completed: http://example.com/file2
高级主题:线程优先级[编辑 | 编辑源代码]
线程优先级(1~10)通过setPriority(int)
设置,但依赖操作系统调度:
Thread highPriorityThread = new Thread(() -> System.out.println("High priority"));
highPriorityThread.setPriority(Thread.MAX_PRIORITY); // 10
总结[编辑 | 编辑源代码]
- Thread类是Java多线程的基础,支持继承或实现Runnable两种创建方式。
- 核心方法控制线程生命周期(启动、休眠、中断等)。
- 实际应用中需注意线程安全与资源竞争问题(后续章节介绍同步机制)。