1

このように、2つの異なるクラスに2つのメソッドがあります

public class ClassX implements Runnable {

    public  void methodAandB() {
        for(int i=0;i<10;i++) {
            System.out.println("This is A and B ");
        }
    }
    @Override
    public void run() {
        methodAandB();
    }
}

public class ClassY implements Runnable {

    public void methodAorB() {
        for(int i=0;i<10;i++) {
            System.out.println("This is A or B");
        }
    }

    @Override
    public void run() {
        methodAorB(a);
    }
}

スレッドt1が を呼び出してmethodAandB()います。

スレッドt2が を呼び出してmethodAorB()います。


メソッド内のループを繰り返すたびに、これら 2 つのスレッドを切り替えることはできますか?

次のような出力を取得したい:

こちらはAとB

これはAかB

こちらはAとB

これはAかB

こちらはAとB

これはAかB

こちらはAとB

これはAかB

4

5 に答える 5

0

これはおそらく問題を解決するのに必要以上のものですが、並行プログラミング演習の紹介であるように思われるため、遭遇する内容に沿っているはずです。

両方のスレッドがそれを介して同期できるように、両方のスレッドが認識している共有オブジェクトが必要です。そのようです:

public class MyMutex {
    private int whoGoes;
    private int howMany;

    public MyMutex(int first, int max) {
        whoGoes = first;
        howMany = max;
    }

    public synchronized int getWhoGoes() { return whoGoes; }

    public synchronized void switchTurns() {
        whoGoes = (whoGoes + 1) % howMany;
        notifyAll();
    }

    public synchronized void waitForMyTurn(int id) throws
            InterruptedException {
        while (whoGoes != id) { wait(); }
    }
}


これで、クラスはそれぞれの識別子とこの共有オブジェクトを受け取るはずです。

public class ClassX implements Runnable {
    private final int MY_ID;
    private final MyMutex MUTEX;

    public ClassX(int id, MyMutex mutex) {
        MY_ID = id;
        MUTEX = mutex;
    }

    public void methodAandB() {
        for(int i = 0; i < 10; i++) {
            try {
                MUTEX.waitForMyTurn(MY_ID);
                System.out.println("This is A and B ");
                MUTEX.switchTurns();
            } catch (InterruptedException ex) {
                // Handle it...
            }
        }
    }
    @Override
    public void run() { methodAandB(); }
}

ClassY同じことをすべきです。順番を待ち、アクションを実行し、順番を相手に譲ります。

于 2013-03-20T17:58:16.100 に答える
-3

Thread を使用する必要がない場合は、次のコードを試してください。

for (int i = 0; i < 20; i++) {
    if (i % 2 == 0) {
        methodAandB();
    } else {
        methodAorB();
    }
}
于 2013-03-20T17:33:33.890 に答える