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

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

    You really need to leave more info.

    You cannot stop other system processes from executing unless you run on a real-time OS. Is that what you mean?

    You cannot stop garbage collection, etc unless you run a real-time java. Is that what you wanted?

    The only thing left is: If you simply want all YOUR other java threads to not interrupt each other because they all tend to access some resource willy-nilly without control, you are doing it wrong. Design it correctly so that objects/data that NEED to be accessed in a synchronized manner are synchronized then don't worry about other threads interrupting you because your synchronized objects are safe.

    Did I miss any possible cases?

提交回复
热议问题