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

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

    Assuming you're only concerned with application-level thread contention, and assuming you are willing to fuss with locks as suggested by others (which, IMHO, is a really bad idea), then you should use a ReadWriteLock and not simple object synchronization:

    import java.java.util.concurrent.locks.*;
    
    // create a fair read/write lock
    final ReadWriteLock rwLock = new ReentrantReadWriteLock(true);
    
    // the main thread grabs the write lock to exclude other threads
    final Lock writeLock = rwLock.writeLock();
    
    // All other threads hold the read lock whenever they do 
    // *anything* to make sure the writer is exclusive when 
    // it is running. NOTE: the other threads must also 
    // occasionally *drop* the lock so the writer has a chance 
    // to run!
    final Lock readLock = rwLock.readLock();
    
    new Thread(new Runnable() {
      public void run() {
        while(condition) {
    
          writeLock.lock();
          try {
            *code that must not be interrupted*
          } finally {
            writeLock.unlock();
          }
    
          *some more code*
        }
      }
    }).start();
    
    new SomeOtherThread(readLock).start();
    new YetAntherThread(readLock).start();
    

提交回复
热议问题