本文介绍了如何在java中确保代码块不会被任何其他线程中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

new Thread(new Runnable() {
  public void run() {
    while(condition) {

      *code that must not be interrupted*

      *some more code*
    }
  }
}).start();

SomeOtherThread.start();

YetAntherThread.start();

如何确保不得中断的代码不会被打断了?

How can you ensure that code that must not be interrupted won't be interrupted?

推荐答案

你不能 - 至少不能使用普通的Java,正常,非实时运行操作系统。即使其他线程不打断你的,其他进程也可能会这样做。基本上,在完成之前,您将无法保证自己获得CPU。如果你想要这种保证,你应该使用像Java Real-Time System这样的东西。我不知道它是否肯定会提供你想要的设施。

You can't - at least not with normal Java, running on a normal, non-real-time operating system. Even if other threads don't interrupt yours, other processes might well do so. Basically you won't be able to guarantee that you get a CPU all to yourself until you're done. If you want this sort of guarantee you should use something like Java Real-Time System. I don't know enough about it to know whether that would definitely provide the facility you want though.

最好的要做的事情就是避免这个要求首先。

The best thing to do is avoid that requirement in the first place.

这篇关于如何在java中确保代码块不会被任何其他线程中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 00:02