gpt4 book ai didi

Java8;在一个线程上利用 sleep 时间,但可调用多个线程

转载 作者:行者123 更新时间:2023-12-02 09:03:01 25 4
gpt4 key购买 nike

标准 java8 中是否可以在单线程上同时执行多个可调用对象?
即当一个可调用对象 hibernate 时,开始处理其他可调用对象。

我当前的实验不起作用:

    ExecutorService executor = Executors.newSingleThreadExecutor();
List<Future> fs = new ArrayList<>();
for (int i = 0; i < 2; i++) {
final int nr = i;
fs.add(executor.submit(() -> {
System.out.println("callable-" + nr + "-start");
try { Thread.sleep(10_000); } catch (InterruptedException e) { }
System.out.println("callable-" + nr + "-end");
return nr;
}));
}
try { executor.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { }

结果:

callable-0-start
callable-0-end
callable-1-start
callable-1-end

我想要:

callable-0-start
callable-1-start
callable-0-end
callable-1-end

注释:

  • 我有点期待一个答案:“不,这是不可能的。这不是线程的工作方式。一旦线程被分配给某些可执行代码,它就会运行直到完成、异常或取消。可调用之间不能进行中途切换/runnables。Thread.sleep 只允许其他线程在CPU/核心上运行。” (明确的确认会让我安心)
  • 当然,这是“玩具”示例。
  • 这是关于理解,而不是我遇到的某个具体问题。

最佳答案

您尝试做的是模拟旧 Java 版本中已弃用的功能。那时可以停止、挂起或恢复线程。但是来自Thread.stop的javadoc:

This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the unchecked ThreadDeath exception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior. Many uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running. If the target thread waits for long periods (on a condition variable, for example), the interrupt method should be used to interrupt the wait.

正如此内容所述,做您想做的事情的风险非常大,因此这种行为已被弃用。

我建议,您应该考虑一个 ThreadPool API,它允许您正确打包代码段,以便它们的状态可以是从线程中卸载,稍后恢复。例如创建 Ticket,这将是一项基本作业,一个线程始终会在开始另一个线程之前完成该作业,这是一个按顺序连接票证并存储状态的 TicketChain。然后制作一个处理程序来一一处理票证。如果当前无法完成票证(例如,因为并非所有数据都存在,或者无法获取某些锁),则线程可以跳过它,直到稍后的时间点,此时所述条件可能为真。

关于Java8;在一个线程上利用 sleep 时间,但可调用多个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60564982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com