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

前端 未结 11 1532
灰色年华
灰色年华 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 10:50

    Just start your own sub-thread, and make sure that the interrupt calls never filter through to it.

    new Thread(new Runnable() {
      public void run() {
        Thread t = new Thread() {
          public void run() {
            *code that must not be interrupted*
          }
        }
        t.start(); //Nothing else holds a reference to t, so nothing call call interrupt() on it, except for your own code inside t, or malicious code that gets a list of every live thread and interrupts it.
    
          while( t.isAlive() ) {
            try {
              t.join();
            } catch( InterruptedException e ) {
              //Nope, I'm busy.
            }
          }
    
          *some more code*
        }
      }
    }).start();
    
    SomeOtherThread.start();
    
    YetAntherThread.start();
    

提交回复
热议问题