-1

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();
    }
}
4

1 に答える 1

1

自分が行っていることの半分を行う必要はありませんが、本当に行う必要があることの 1 つは、コントロールを共有することです。現時点では、各スレッドは独自のコントロールを作成します。つまり、スレッドは相互作用していません。

したがって、コードをフォーマットして不要なものの半分を削除し、AtomicBoolean を共有すると、作業にかなり近づきます。

于 2013-08-20T18:24:08.133 に答える