0

I have a while loop in a method. In that while loop I have many if blocks. If I have 2 threads accessing one while loop at the same time how to stop one a unique if block at the same time. Should i have to import any thing?

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{//}
              }
     }
Sathiyakugan
  • 674
  • 7
  • 20
  • Use [`synchronized` block](https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html) – Jiri Tousek Nov 05 '16 at 12:42
  • Hint: so many cascaded if/else statements are a clear sign of a bad design. Consider studying a good book like "Clean code" by Robert Martin if you are interested in bumping the quality of your code! I guarantee you: such complex conditional logic, combined with multi-threading ... will blow your mind. You can spent hours trying to get it right, but it will turn out ... to not be. Seriously: **first** simplify your code, then add the multi-threading part. Doing it in reverse order means that you will spend 5, 10 times more time than you ought to. – GhostCat Nov 05 '16 at 14:39
  • Really Yo are right! thanks guiding me! I want more guidance from you! thanks a lot! – Sathiyakugan Nov 05 '16 at 15:11
  • @eagle While synchronized or lock or semaphore would solve your problem, this is a terrible design. These multiple if-else bolcks would never maintenance friendly. – Supun Wijerathne Nov 07 '16 at 03:16
  • 1
    @SupunWijerathne thanks a lot bro! your kind replies will lead me! I just wanna guidance like this! – Sathiyakugan Nov 07 '16 at 16:26

1 Answers1

1

There are several ways to achieve that but why don't you try a 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{//}
}
adam12
  • 91
  • 1
  • 2