如何在java中确保代码块不会被任何其他线程中断

11 java multithreading synchronization thread-priority

为例:

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

      *code that must not be interrupted*

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

SomeOtherThread.start();

YetAntherThread.start();
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*eet 14

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

最好做的事情是避免在首位这一要求.


kro*_*old 0

最好的中途解决方案是同步某个公共对象上的所有线程,以便当您位于关键部分时没有其他线程可运行。

除此之外我认为这是不可能的。我很好奇什么样的问题需要这种类型的解决方案?