3

スレッドの仕組みを理解するのに問題があります:

class ThreadTest implements Runnable{ 
    synchronized void methodA(long n){ 
        for (int i=1;i<3;i++){System.out.print(n+" "+i)} 
    } 

    public void run(){ 
        methodA(Thread.currentThread.getId()); 
    } 

    public static void main(String ... args){ 
        new Thread(new ThreadTest()).start(); 
        new Thread(new ThreadTest()).start(); 
    } 
} 

私が現在理解しているようにmethodA、このメソッドは同期された for ループであるため、次のスレッドがこのメソッドを呼び出す前に終了する必要があります-したがって、結果は次のようになります4-1 4-2 5-1 5-2...

のような結果になる可能性はあり4-1 5-1 5-2 4-2ますか? はいの場合、どのように?

4

2 に答える 2

13

Is it possible to have result like 4-1 5-1 5-2 4-2.?

It is possible.

If yes how?

You are using the this reference as the object which is locked by synchronized. Since you've got two distinct instances of ThreadTest, each method locks its own instance and mutual exclusion is not achieved.

So, what you must understand is the semantics of synchronized: there is always a clearly defined object involved whose monitor is acquired. Basically, that object notes which thread has acquired its monitor and will allow only the same thread to re-acquire it; other threads will be put on hold until the monitor is released. Any other object, naturally, has nothing to do with this and its monitor is free to be acquired by any thread.

A synchronized method implicitly uses this for the lock. What you can do for your example is declare a static final Object lock = new Object(); and use synchronized(lock) in your method.

于 2013-05-18T18:35:21.267 に答える