0

我在一个方法中有一个while循环。在那个 while 循环中,我有很多 if 块。如果我有 2 个线程同时访问一个 while 循环,如何同时停止一个唯一的 if 块。我应该进口任何东西吗?

while (true){
     if (condition){
              if (statement 1){//}
              else if (statement){//} //I want only one thread to access this block at a time
              else if (statement2 ){//}
              else{//}
     }

     else if condition1 ){
              if (statement 1){//}
              else if (statement){//} //I want only one thread to access this block at a time
              else if (statement2 ){//}
              else{//}
              }
     }

    else if (condition 2){
              if (statement 1){//}
              else if (statement){//} //I want only one thread to access this block at a time
              else if (statement2 ){//}
              else{//}
              }
     }

    else{
              if (statement 1){//}
              else if (statement){//} //I want only one thread to access this block at a time
              else if (statement2 ){//}
              else{//}
              }
     }
4

1 回答 1

1

有几种方法可以实现这一点,但为什么不尝试同步块呢?

while(true) {
   if (statement){//}
   else if (statement){ //I want only one thread to access this block at a time
      synchronized(this) {
         //your critical section here
      }
   }
   else if (statement){//}
   else{//}
}
于 2016-11-05T13:28:54.513 回答