【问题标题】:Block 2 threads accessing one if block in java在java中阻止2个线程访问一个if块
【发布时间】:2016-11-05 12:35:42
【问题描述】:

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

【问题讨论】:

  • 提示:如此多的级联 if/else 语句是糟糕设计的明显标志。如果您对提高代码质量感兴趣,可以考虑学习一本好书,例如 Robert Martin 的“清洁代码”!我向你保证:如此复杂的条件逻辑,结合多线程......会让你大吃一惊。你可以花几个小时试图把它弄好,但结果会……不是。说真的:首先简化您的代码,然后添加多线程部分。以相反的顺序进行操作意味着您将花费 5 到 10 倍的时间。
  • 真的哟是对的!谢谢指导我!我希望得到你更多的指导!非常感谢!
  • @eagle 虽然同步或锁定或信号量可以解决您的问题,但这是一个糟糕的设计。这些多个 if-else 块永远不会维护友好。
  • @SupunWijerathne 非常感谢兄弟!您的友好回复将引导我!我只是想要这样的指导!

标签: java multithreading locking synchronized synchronized-scrolling


【解决方案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{//}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-07
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多