
本文深入探讨了java多线程编程中一个常见的陷阱:当使用`executorservice`时,如果任务类不当地在`run()`方法内部创建新的`thread`实例,会导致输出重复或行为异常。文章通过分析问题代码,揭示了将任务定义为`runnable`接口实现而非直接继承`thread`,并正确使用`thread.currentthread().getname()`获取当前执行线程名称的重要性。通过遵循这些最佳实践,可以有效避免多线程环境下的逻辑混乱和资源浪费,确保程序行为符合预期。
在Java多线程应用开发中,尤其是在使用线程池(ExecutorService)管理任务时,开发者可能会遇到线程行为异常或输出重复的问题。一个典型的场景是,尽管我们期望每个任务只执行一次并输出相应信息,但实际运行结果却显示某些任务(尤其是最后一个)的信息被重复打印多次。这通常是由于对Java线程模型和ExecutorService工作原理的误解所导致的。
考虑以下代码示例,它尝试使用线程池来模拟一系列随机休眠的任务:
sampleThread.java (原始问题代码)
import java.util.Random;
public class sampleThread extends Thread {
sampleThread thread; // 声明一个实例变量
Random rand = new Random();
public void run() {
thread = new sampleThread(); // 在run方法内创建新的sampleThread实例
int randSleep = rand.nextInt(1000);
System.out.println(thread.getName() + " is sleeping for " + randSleep + " milliseconds");
try {
Thread.sleep(randSleep);
System.out.println(thread.getName() + " is NOW AWAKE");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}driver.java (原始问题代码)
立即学习“Java免费学习笔记(深入)”;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class driver {
public static void main(String[] args) throws ExecutionException, InterruptedException {
List<Future<?>> futArray = new ArrayList<>();
ExecutorService es = Executors.newFixedThreadPool(6); // 创建一个固定大小为6的线程池
sampleThread temp = new sampleThread(); // 创建一个sampleThread实例
for (int i = 0; i < 120; i++) {
Future<?> future = es.submit(temp); // 将同一个temp实例提交120次
futArray.add(future);
}
// ... 后续可能还有关闭线程池等操作
}
}当运行上述代码时,我们可能会观察到如下输出:
Thread-117 is sleeping for 547 milliseconds Thread-117 is NOW AWAKE Thread-118 is sleeping for 442 milliseconds Thread-118 is NOW AWAKE Thread-119 is sleeping for 182 milliseconds Thread-119 is NOW AWAKE Thread-120 is sleeping for 487 milliseconds Thread-120 is NOW AWAKE Thread-120 is NOW AWAKE Thread-120 is NOW AWAKE Thread-120 is NOW AWAKE Thread-120 is NOW AWAKE Thread-120 is NOW AWAKE
可以看到,最后一条线程的“NOW AWAKE”信息被重复打印了多次,这与预期不符。
这个问题的核心在于对Thread类的不当使用以及在run()方法内部创建新线程实例的错误操作。
不当的Thread继承与实例化:
线程名称的混淆:
解决此问题的关键在于遵循Java并发编程的最佳实践:
实现Runnable接口而非继承Thread类: 当使用ExecutorService时,任务通常应该实现Runnable接口。ExecutorService负责管理底层的线程,我们只需要提供任务逻辑。继承Thread类通常只在需要重写Thread的特定行为时才考虑,但对于简单的任务执行,Runnable更简洁且更符合职责分离原则。
获取当前执行线程的名称: 要获取当前正在执行run()方法的线程的名称,应使用静态方法Thread.currentThread().getName()。这会返回执行当前代码块的线程的实际名称,而不是某个特定Thread实例的名称。
以下是修改后的sampleThread类:
sampleThread.java (修正版)
import java.util.Random;
// 1. 实现Runnable接口
public class sampleThread implements Runnable {
Random rand = new Random();
public void run() {
// 2. 移除在run方法内创建新sampleThread实例的代码
// 3. 使用Thread.currentThread().getName() 获取当前执行线程的名称
String threadName = Thread.currentThread().getName();
int randSleep = rand.nextInt(1000);
System.out.println(threadName + " is sleeping for " + randSleep + " milliseconds");
try {
Thread.sleep(randSleep);
System.out.println(threadName + " is NOW AWAKE");
} catch (InterruptedException e) {
// 最佳实践:在捕获InterruptedException后,重新设置中断标志
Thread.currentThread().interrupt();
System.err.println(threadName + " was interrupted while sleeping.");
// 可以选择抛出RuntimeException,或者更优雅地处理中断
// throw new RuntimeException(e);
}
}
}driver.java (修正版)
driver.java中的修改主要在于提交任务时,每次循环都创建一个新的sampleThread实例,因为Runnable实例代表一个独立的任务。
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class driver {
public static void main(String[] args) throws ExecutionException, InterruptedException {
List<Future<?>> futArray = new ArrayList<>();
ExecutorService es = Executors.newFixedThreadPool(6); // 创建一个固定大小为6的线程池
for (int i = 0; i < 120; i++) {
// 每次循环创建一个新的Runnable实例
sampleThread task = new sampleThread();
Future<?> future = es.submit(task); // 提交不同的task实例
futArray.add(future);
}
// 确保所有任务完成,并关闭线程池
for (Future<?> future : futArray) {
future.get(); // 阻塞直到任务完成
}
es.shutdown(); // 启动有序关闭
if (!es.awaitTermination(60, java.util.concurrent.TimeUnit.SECONDS)) {
es.shutdownNow(); // 如果超时,则强制关闭
}
System.out.println("All tasks completed and ExecutorService shut down.");
}
}现在,运行修正后的代码,输出将是这样的:
pool-1-thread-1 is sleeping for 526 milliseconds pool-1-thread-6 is sleeping for 497 milliseconds pool-1-thread-4 is sleeping for 565 milliseconds pool-1-thread-5 is sleeping for 978 milliseconds pool-1-thread-2 is sleeping for 917 milliseconds pool-1-thread-3 is sleeping for 641 milliseconds pool-1-thread-6 is NOW AWAKE pool-1-thread-6 is sleeping for 847 milliseconds pool-1-thread-1 is NOW AWAKE pool-1-thread-1 is sleeping for 125 milliseconds // ... (其他线程的交错输出) pool-1-thread-3 is NOW AWAKE pool-1-thread-5 is NOW AWAKE pool-1-thread-6 is NOW AWAKE pool-1-thread-4 is NOW AWAKE pool-1-thread-1 is NOW AWAKE pool-1-thread-2 is NOW AWAKE pool-1-thread-3 is NOW AWAKE All tasks completed and ExecutorService shut down.
可以看到,输出现在清晰地显示了线程池中的6个工作线程(如pool-1-thread-1到pool-1-thread-6)轮流执行任务,并且每个任务的“NOW AWAKE”信息只打印一次,符合预期。
Runnable vs. Thread:
ExecutorService的正确使用:
获取当前线程:Thread.currentThread()是一个静态方法,它返回当前正在执行代码的线程对象的引用。这是获取线程名称、检查中断状态等操作的正确方式。
异常处理: 在run()方法中捕获InterruptedException时,最佳实践是在捕获后重新设置线程的中断标志(Thread.currentThread().interrupt();),以便上层调用者能够感知到中断。
理解Java多线程中的Thread和Runnable的区别,以及ExecutorService的工作机制,对于编写健壮、高效的并发程序至关重要。避免在run()方法内部错误地创建新的Thread实例,并始终使用Thread.currentThread().getName()来获取当前执行线程的名称,是避免多线程环境中常见陷阱的关键。通过遵循这些原则,开发者可以更好地控制线程行为,确保程序的正确性和可预测性。
以上就是Java多线程中重复输出的常见陷阱与解决方案的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号