我希望解决 Java 中的临界区问题。第一个过程进入无限while循环,该循环应该以状态之间的控制变化而结束,这会导致turn变量被重置。但是第二个线程似乎没有完成它的工作。谁能告诉我为什么以及如何解决它?
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
class ty{
class Control{
public volatile AtomicBoolean turn=new AtomicBoolean();
}
final Control control=new Control();
}
class newthread implements Runnable{
Thread g;
ty t=new ty();
newthread(){
g=new Thread(this,"hello");
g.start();
}
@Override
public synchronized void run(){
while ((t.control.turn).get()==false){
try {
g.sleep(2000);
}
catch (InterruptedException ex) {
Logger.getLogger(newthread.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("process "+t.control.turn+"is executing");
}
System.out.println("process "+ t.control.turn+ " is executing");
(t.control.turn).compareAndSet(false, true);
}
}
class newthreadt implements Runnable{
Thread g;
ty t=new ty();
newthreadt(){
g=new Thread(this,"hello1");
g.start();
}
@Override
public synchronized void run(){
while ((t.control.turn).get()==true){
try {
g.sleep(1000);
} catch (InterruptedException ex){
Logger.getLogger(newthreadt.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("process "+t.control.turn+"is executing");
}
System.out.println("process "+t.control.turn+"is executing");
(t.control.turn).compareAndSet(true, false);
}
}
public class JavaApplication2 {
public static void main(String[] args){
int turn=0;
newthread f;
newthreadt g;
new newthread();
new newthreadt();
}
}