How can you ensure in java that a block of code can not be interrupted by any other thread

前端 未结 11 1546
灰色年华
灰色年华 2021-01-04 10:02

exampl:

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

      *code that must not be interrupted*

      *some more code*
    }
  }         


        
11条回答
  •  甜味超标
    2021-01-04 11:03

    Actually, you can do this if you control the thread instance you are running on. Obviously, there are a ton of caveats on this (like hanging io operations), but essentially you can subclass Thread and override the interrupt() method. you can then put some sort of boolean in place such that when you flip a flag, interrupt() calls on your thread are either ignored or better yet stored for later.

提交回复
热议问题