java - 发送到 scheduleAtFixedRate 时线程名称不匹配
问题描述
我创建了一个可运行的类并创建了一个线程,但具有唯一的名称,但是当我发送这个线程时,虽然executor.scheduleAtFixedRate
它创建了自己的线程,但我不明白为什么会这样?
我试图在这里阅读,但我仍然不明白: https ://www.codejava.net/java-core/concurrency/java-concurrency-scheduling-tasks-to-execute-after-a-given-delay-或定期
public class Main {
public static void main(String[] args) throws ClassNotFoundException {
ScheduledExecutorService executor =
Executors.newSingleThreadScheduledExecutor();
Runnable runnable = new AutoUpdater();
Thread thread = new Thread(runnable, "MyThread");
executor.scheduleAtFixedRate(thread, 0, 24, TimeUnit.HOURS);
}
}
public class AutoUpdater implements Runnable {
public void run() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " is running...");
System.out.println("Thread ended.\n");
}
}
它应该打印名称 MyThread 但输出是:
pool-1-thread-1
它应该是这样的:
pool-1-MyThread-1
解决方案
问题是Executors.newSingleThreadScheduledExecutor()
创建了一个在内部拥有自己线程的池。
当你看ScheduledExecutorService::scheduleAtFixedRate
它时,它Runnable
作为第一个论点。这Runnable
将由池中的某个线程运行。请注意,Thread
实现Runnable
并且您将Thread
实例传递给scheduleAtFixedRate
方法,因此该线程的 run 方法将被其他线程调用,但您传递的线程将不会被启动。一般来说,为了避免任何误解,你应该Runnable
在这里传递简单的,这将代表需要完成的工作。
如果要更改此池中的线程名称,则必须提供 customThreadFactory
将由池用于创建新线程:
ThreadFactory threadFactory = runnable -> new Thread(runnable, "MyThreadName");
ScheduledExecutorService executor =
Executors.newSingleThreadScheduledExecutor(threadFactory);
编辑:
对于 < 8 的 Java 版本,我们可以简单地创建新的类实现ThreadFactory
接口:
class MyThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable runnable) {
return new Thread(runnable, "MyThreadName");
}
}
然后通过它:
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(new MyThreadFactory());
推荐阅读
- discord.py - Discord.py - 如果提到特定用户,如何删除消息
- amazon-web-services - Elastic Beanstalk 中的权限被拒绝
- html - 如何在 html 和 Angular 中创建动态表
- python - Python - Flask-Restful 中的 Scipy 优化和返回值
- php - 解析“Symfony\Component\Form\Extension\Core\Type\PasswordType”形式的选项时发生错误:选项“0”、“1”不存在
- python-3.x - 如何在python3中拆分列表项并保存在csv文件中
- python - TypeError:“模块”对象在 InceptionResNetV2 Keras 中不可调用
- sql-workbench-j - SQL Workbench/J WbDataDiff 时间戳
- java - Java,我无法在控制台上打印整个响应
- sas - 有没有办法轻松地将 PROC LTA 的输出保存到 SAS 中的 MS Word 文档中?