Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如果某个特定线程';他跑得太久了?_Java_Multithreading_Interrupt_Executor - Fatal编程技术网

Java 如果某个特定线程';他跑得太久了?

Java 如果某个特定线程';他跑得太久了?,java,multithreading,interrupt,executor,Java,Multithreading,Interrupt,Executor,到目前为止,在我对executorservice的实验中,我得到了很多建议,包括使用future.get,然后使用future.cancel,以便抛出一个线程中断,然后需要在线程中捕获该中断,并在那里进行处理。我的问题有点不同 假设我正在运行一个线程,该线程只跟踪事物运行的时间,如果它们超过某个阈值,这是杀死executorservice和所有正在运行的线程的好方法吗 思维过程示例: ExecutorService threadPool = Executors.newFixedThreadPoo

到目前为止,在我对executorservice的实验中,我得到了很多建议,包括使用future.get,然后使用future.cancel,以便抛出一个线程中断,然后需要在线程中捕获该中断,并在那里进行处理。我的问题有点不同

假设我正在运行一个线程,该线程只跟踪事物运行的时间,如果它们超过某个阈值,这是杀死executorservice和所有正在运行的线程的好方法吗

思维过程示例:

ExecutorService threadPool = Executors.newFixedThreadPool(12);
timekeeper.start();
List<Future<?>> taskList = new ArrayList<Future<?>>();
    for (int i = 0; i < objectArray.length; i++) {
        Future<?> task = threadPool.submit(new ThreadHandler(objectArray[i], i));
        taskList.add(task);
        Thread.sleep(500);
    }

if(timekeeper.now() > 60)
    threadpool.shutdownNow();
}
ExecutorService线程池=Executors.newFixedThreadPool(12);
计时器。开始();
列表>();
for(int i=0;i60)
threadpool.shutdownNow();
}

这样行吗?我没有办法检查,因为我的线程很少失败(大约1/700次运行,并且只有在一天中的某些时间我不工作时才会失败)。

这就是我要做的

ExecutorService threadPool = Executors.newFixedThreadPool(12);
List<Future<?>> taskList = new ArrayList<Future<?>>();
for (int i = 0; i < objectArray.length; i++) {
    taskList.add(threadPool.submit(new ThreadHandler(objectArray[i], i)));
threadPool.shutdown();
threadPool.awaitTermination(60, TimeUnit.SECONDS); // or what ever
threadPool.shutdownNow();
ExecutorService线程池=Executors.newFixedThreadPool(12);
列表>();
for(int i=0;i
这假设您的任务将尊重中断。如果不尊重中断,则没有干净的方法来终止线程(除了使用与此基本相同的标志)


不使用Thread.stop()的原因

  • 您无权访问要调用stop()的线程对象
  • 如果任务是ignores interrupt(),则它很可能表现不佳,这会使堆处于损坏状态
  • 调用stop()应该停止任务,但不会停止线程池线程,除非它在捕获线程池线程时被
    shutdown()

shutdownNow
方法尝试中断所有活动的任务线程,只有当任务被编码为受尊重的中断时,这才有效。它们需要:

  • 检查是否在长时间运行的循环中设置了中断标志,以及

  • 正确处理中断异常

基本上,任务需要合作,中断才能工作。如果它们不合作,除了退出JVM之外,没有安全可靠的方法来阻止它们



上面有人提到了.stop()方法作为注释,您能提供注释说明为什么这是个坏主意吗


这种方法是因为它从根本上是不安全的。停止线程会使关键数据结构处于中间状态,并会干扰以各种方式与它交互的其他线程。理论上可以安全地使用
stop
,但很难制定出一组通用的先决条件足以确保不会发生任何坏事。

我知道最有效的杀戮方法是.stop()方法,已被弃用,但它仍然有效。如果有人提到.stop()方法作为注释,你能提供注释说明为什么这是个坏主意吗?