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

前端 未结 11 1571
灰色年华
灰色年华 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:00

    A usual program does not randomly interrupt threads. So if you start a new Thread and you are not passing the reference to this Thread around, you can be quite sure that nothing will interrupt that Thread.

    Keep the reference to the Thread private is sufficient in most scenarios. Everything else would be hacky.

    Typically work queues like ExecutorService will interrupt their Thread's when asked to do so. In these cases you want to deal with interrupts.

提交回复
热议问题