1

これが私が問題を抱えているコードです-

public class WaitTest {
    public static void main(String[] args) {
        Runner rr = new Runner();
        Thread t1 = new Thread(rr,"T1");
        Thread t2 = new Thread(rr,"T2");
        t1.start();
        t2.start();
    }
}

class Runner implements Runnable{
    int i=0;
    public void run(){
        try{
            if(Thread.currentThread().getName().equals("T1")){
                bMethod();
                aMethod();
            }
            else{
                aMethod();
                bMethod();
            }
        }catch(Exception e){}
    }

    public synchronized void aMethod() throws Exception{
        System.out.println("i="+i+",Now going to Wait in aMethod "+Thread.currentThread().getName());
        Thread.currentThread().wait();
        System.out.println("Exiting aMethod "+Thread.currentThread().getName());
    }

    public synchronized void bMethod() throws Exception{
        System.out.println("i="+i+",Now going to Wait bMethod "+Thread.currentThread().getName());
        i=5;
        notifyAll();
        System.out.println("Exiting bMethod "+Thread.currentThread().getName());
    }
}

出力は次のとおりです。

i=0,Now going to Wait bMethod T1
Exiting bMethod T1
i=5,Now going to Wait in aMethod T1
i=5,Now going to Wait in aMethod T2

私の質問は:

内部で待機してaMethodいるときにT2が入るのはなぜですか?T1となぜT2印刷 i=5するのかaMethod.

4

3 に答える 3

4

When you execute wait, your thread releases the lock and enters the wait state. At this time the other thread is allowed to enter the method. You are using a single instance of Runnable so when one thread sets it to 5, that's what the other thread reads.

于 2012-07-15T11:40:02.670 に答える
2

1. wait will immediately release the lock, and handover the lock to the other thread.

2. notify will release the lock only when the closing parenthesis of the synchronized block is reached.

3. As there is only one instance of Runnable here, its after the i = 5, and when the synchronized block ends..then the lock is released.

于 2012-07-15T11:43:33.190 に答える
0

This code is not doing the wait-notify pattern. The Thread.currentThread().wait() call throws an IllegalMonitorStateException, which is caught and ignored by the run method. Both T1 and T2 throws this exception, and hence you do not see the line Exiting aMethod printed.

The notify call in bMethod is wasted, because no thread ever waits on the intrinsic lock of the rr Runnable.

于 2012-07-19T08:02:01.213 に答える