java - java中 block 2个线程访问一个if block

标签 java multithreading locking synchronized synchronized-scrolling

我的方法中有一个 while 循环。在那个 while 循环中,我有很多 if block 。如果我有 2 个线程同时访问一个 while 循环,如何同时停止一个唯一的 if block 。我需要导入任何东西吗?

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{//}
              }
     }

最佳答案

有多种方法可以实现这一目标,但为什么不尝试使用同步块(synchronized block)呢?

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{//}
}

关于java - java中 block 2个线程访问一个if block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40438321/

相关文章:

java - 如何从主应用程序外部化语言属性和模板?

java - 如何防止 CompletableFuture#whenComplete 在上下文线程中执行

mysql - 由于 SELECT FOR UPDATE 在没有事务的情况下毫无意义,并且事务本身使用锁,因此 SELECT FOR UPDATE 的用例是什么?

linux - 避免同一 bash 脚本的两个实例

c++ - 使用 std::try_to_lock 的意外行为

java - JSP日期默认值

java - IllegalArgumentException:Java Constructor.newInstance() 中的参数数量错误

java - 过时元素引用异常 : How to solve?

multithreading - 我可以使用 Boost 消息队列进行线程通信吗

java - 单例 Spring Controller 中的依赖范围