块2线程访问java中的一个if块

时间:2016-11-05 12:35:42

标签: java multithreading locking synchronized synchronized-scrolling

我在方法中有一个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{//}
              }
     }

1 个答案:

答案 0 :(得分: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{//}
}