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