提问人:Ufuk Mirza Yüksel 提问时间:11/7/2023 更新时间:11/7/2023 访问量:43
线程和多线程结构问题
Thread and MultiThread structure issue
问:
我正在努力总结我的问题,因为在提出解决方案之前可能需要提出一些问题。我会尽力回答任何疑问。
我有一系列函数: 这些函数在 try 块中调用,如下所示:A(), B(), C(), D().
void CalculateX() {
try {
A();
B();
C();
D();
} catch (...) {
// handle exceptions
} finally {
E();
}
}
此 try 块中的函数在不同的硬件线程上处理。我正在从 React Native 调用 CalculateX 函数。为了避免锁定UI或造成延迟,CalculateX需要在单独的线程上执行。每次在 React 界面中单击按钮时,都会调用 CalculateX 函数。这是我想出的一个解决方案(代码不是“干净的”,但我的首要任务是解决问题):
class TaskExecutor {
static ExecutorService singleTaskExecutor = Executors.newSingleThreadExecutor();
static CountDownLatch latch;
@ReactMethod
static void displaySale(String msg_1, String msg_2, Context reactContext, QuarkCallback callback, FiscalPrinterExecuter fiscalPrinterExecuter, LogModule log) throws InterruptedException {
singleTaskExecutor.submit(() -> {
try {
if(latch!=null || latch.getCount()>0)
latch.await();
latch = new CountDownLatch(1);
A();
B();
C();
// ... other calls
} catch (FiscalException | InterruptedException e) {
// log.addRecordToLogJ("Fiscal Error or Interruption");
} finally {
E();
}
});
}
}
正如预期的那样,当闩锁的计数达到 1 并调用 latch.wait 时,它会停止执行显示操作的单个线程,从而阻止对此线程进行任何进一步的处理。
现在,我的问题: 功能 A、B、C、D...E 在不同的线程上内部处理(尽管 A、B、C、D 和 E 在同一线程内处理,但它们是库函数的一部分,而库函数又在其一侧管理一个新线程)。由于它们是在不同的线程上处理的,因此调用 A、B、C、D 函数不会等待它们完成(该过程可能需要 3 秒钟,但无需等待即可立即进行)。如何在线程队列中管理它?
注意:E 函数处理硬件,类似于关闭硬件的操作。
注 2:如果 A 函数连续调用两次(中间没有处理 E 函数,如 -> A B C D A),则硬件崩溃。End()
我希望这个线程结构能像我预期的那样工作。
答: 暂无答案
评论
if(latch!=null || latch.getCount()>0)
&&
||