Javaのクリティカルセクションの問題を解決したいと思っていました。最初のプロセスは、状態間の制御の変更で終了する無限 while ループに入り、ターン変数がリセットされます。しかし、2 番目のスレッドは機能していないようです。誰かが理由とそれを修正する方法を教えてもらえますか?
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();
}
}