线程(Thread 类)的常用方法
在 Java 中,线程(Thread 类)提供了许多常用方法,这些方法可以帮助你创建、控制和管理线程。以下是一些常见的线程方法及其使用示例:
1. 线程的创建与启动
Thread():无参构造方法,用于创建一个新的线程对象。Thread(Runnable target):通过传入一个实现了Runnable接口的对象来创建线程。start():启动线程,使线程进入就绪状态,等待 CPU 调度执行其run()方法。
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("线程正在执行,线程名:" + Thread.currentThread().getName());
}
}
public class ThreadCreationExample {
public static void main(String[] args) {
// 使用 Runnable 接口创建线程
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
2. 线程的执行方法
run():线程的执行体,当线程被调度执行时,会调用该方法。通常需要重写此方法来定义线程要执行的任务。
3. 线程的控制方法
sleep(long millis):使当前线程暂停执行指定的毫秒数,进入阻塞状态。该方法是静态方法,会抛出InterruptedException异常。
public class ThreadSleepExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
try {
System.out.println("线程开始睡眠");
Thread.sleep(2000); // 线程睡眠 2 秒
System.out.println("线程睡眠结束");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread.start();
}
}
join():等待调用该方法的线程执行完毕后,当前线程才会继续执行。会抛出InterruptedException异常。
public class ThreadJoinExample {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 3; i++) {
System.out.println("线程 1 执行:" + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(() -> {
try {
thread1.join(); // 等待 thread1 执行完毕
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 3; i++) {
System.out.println("线程 2 执行:" + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
thread2.start();
}
}
yield():静态方法,提示调度器当前线程愿意让出 CPU 资源,让其他具有相同优先级的线程有机会执行。但这只是一个建议,调度器可能会忽略该提示。
public class ThreadYieldExample {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println("线程 1 执行:" + i);
if (i == 2) {
Thread.yield(); // 线程 1 让出 CPU 资源
}
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println("线程 2 执行:" + i);
}
});
thread1.start();
thread2.start();
}
}
4. 线程的状态与优先级
getState():返回线程的当前状态,状态类型定义在Thread.State枚举中,包括NEW、RUNNABLE、BLOCKED、WAITING、TIMED_WAITING和TERMINATED。
public class ThreadStateExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("线程状态:" + thread.getState()); // 输出 NEW
thread.start();
System.out.println("线程状态:" + thread.getState()); // 可能输出 RUNNABLE 或 TIMED_WAITING
}
}
getPriority():返回线程的优先级,范围是 1(最低优先级)到 10(最高优先级),默认优先级是 5。setPriority(int newPriority):设置线程的优先级,可能会影响线程调度的顺序,但不能保证绝对的执行顺序。
public class ThreadPriorityExample {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println("线程 1 执行:" + i);
}
});
thread1.setPriority(Thread.MIN_PRIORITY); // 设置最低优先级
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println("线程 2 执行:" + i);
}
});
thread2.setPriority(Thread.MAX_PRIORITY); // 设置最高优先级
thread1.start();
thread2.start();
}
}
5. 线程的中断
interrupt():中断线程。如果线程处于阻塞状态(如sleep()、join()、wait()等),会抛出InterruptedException异常;如果线程未处于阻塞状态,中断标志会被设置为true。isInterrupted():判断线程的中断标志是否被设置为true。interrupted():静态方法,判断当前线程的中断标志是否被设置为true,并清除中断标志。
public class ThreadInterruptExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("线程正在执行");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("线程被中断,中断标志:" + Thread.currentThread().isInterrupted());
Thread.currentThread().interrupt(); // 重新设置中断标志
}
}
System.out.println("线程停止执行,中断标志:" + Thread.currentThread().isInterrupted());
});
thread.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt(); // 中断线程
}
}
6. 线程的其他方法
currentThread():静态方法,返回当前正在执行的线程对象。
public class CurrentThreadExample {
public static void main(String[] args) {
Thread currentThread = Thread.currentThread();
System.out.println("当前线程名:" + currentThread.getName());
}
}
setName(String name):设置线程的名称。getName():返回线程的名称。
public class ThreadNameExample {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("线程名:" + Thread.currentThread().getName());
});
thread.setName("MyThread");
thread.start();
}
}
这些方法可以帮助你更好地控制和管理线程的执行,根据不同的需求选择合适的方法来实现线程的各种功能。
JUC编程 文章被收录于专栏
JUC 是 Java.util.concurrent 包的简称,它是 Java 5 引入的一个用于处理并发编程的工具包,为 Java 开发者提供了一系列用于高效处理并发任务的类和接口,极大地简化了多线程编程的复杂性。
腾讯成长空间 5877人发布
