Thread
类是用来创建和管理线程的基本工具。下面是一些常用的 Thread
类的方法以及如何使用它们的示例:
1. 线程创建
要创建一个线程,你可以继承 Thread
类并重写它的 run
方法,或者实现 Runnable
接口。
继承 Thread
类的方式:
class MyThread extends Thread { @Override public void run() { System.out.println("线程正在运行"); } } public class Main { public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); // 启动线程 } }
实现 Runnable
接口的方式:
class MyRunnable implements Runnable { @Override public void run() { System.out.println("线程正在运行"); } } public class Main { public static void main(String[] args) { Thread thread = new Thread(new MyRunnable()); thread.start(); // 启动线程 } }
2. 线程中断
你可以使用 interrupt
方法来中断一个线程。中断是线程之间通信的一种方式,它不会立即停止线程的执行,但会设置一个中断标志。你需要在代码中检查这个标志,并在适当的地方处理它。
class MyThread extends Thread { @Override public void run() { try { while (!Thread.currentThread().isInterrupted()) { // 执行任务 System.out.println("线程运行中..."); Thread.sleep(1000); // 休眠1秒 } } catch (InterruptedException e) { System.out.println("线程被中断"); // 清理资源 } } } public class Main { public static void main(String[] args) throws InterruptedException { MyThread thread = new MyThread(); thread.start(); Thread.sleep(3000); // 主线程休眠3秒 thread.interrupt(); // 中断线程 } }
3. 线程等待
使用 wait
方法可以使当前线程等待直到其他线程调用 notify
或 notifyAll
。wait
方法必须在同步代码块或同步方法中调用。
class SharedResource { private boolean available = false; public synchronized void waitForResource() throws InterruptedException { while (!available) { wait(); // 等待资源变为可用 } // 资源可用,进行处理 } public synchronized void releaseResource() { available = true; notify(); // 通知等待的线程资源已经可用 } } public class Main { public static void main(String[] args) { SharedResource resource = new SharedResource(); new Thread(() -> { try { resource.waitForResource(); System.out.println("资源被获取"); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); new Thread(() -> { try { Thread.sleep(2000); // 模拟资源准备时间 resource.releaseResource(); System.out.println("资源已释放"); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); } }
4. 线程休眠
你可以使用 sleep
方法使当前线程休眠一段时间。这不会中断当前线程,它只是暂停线程的执行。
public class Main { public static void main(String[] args) { new Thread(() -> { try { System.out.println("线程休眠开始"); Thread.sleep(2000); // 休眠2秒 System.out.println("线程休眠结束"); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); } }
5. 获取线程实例
可以使用 Thread.currentThread()
方法获取当前正在执行的线程的实例。你也可以使用 Thread.getAllStackTraces()
方法获取所有线程的堆栈信息。
public class Main { public static void main(String[] args) { Thread currentThread = Thread.currentThread(); System.out.println("当前线程名: " + currentThread.getName()); System.out.println("当前线程ID: " + currentThread.getId()); new Thread(() -> { Thread t = Thread.currentThread(); System.out.println("新线程名: " + t.getName()); }).start(); } }