2016-10-10 65 views

回答

1

取決於。如果方法是靜態的,那麼它們在類對象上同步,並且交織是不可能的。如果它們是非靜態的,那麼它們在this對象上同步並且可能進行交織。以下示例應該說明行爲。

import java.util.ArrayList; 
import java.util.List; 

class Main { 
    public static void main(String... args) { 
    List<Thread> threads = new ArrayList<Thread>(); 

    System.out.println("----- First Test, static method -----"); 
    for (int i = 0; i < 4; ++i) { 
     threads.add(new Thread(() -> { 
     Main.m1(); 
     })); 
    } 
    for (Thread t : threads) { 
     t.start(); 
    } 
    for (Thread t : threads) { 
     try { 
     t.join(); 
     } catch (InterruptedException e) { 
     e.printStackTrace(); 
     } 
    } 

    System.out.println("----- Second Test, non-static method -----"); 
    threads.clear(); 
    for (int i = 0; i < 4; ++i) { 
     threads.add(new Thread(() -> { 
     new Main().m2(); 
     })); 
    } 
    for (Thread t : threads) { 
     t.start(); 
    } 
    for (Thread t : threads) { 
     try { 
     t.join(); 
     } catch (InterruptedException e) { 
     e.printStackTrace(); 
     } 
    } 

    System.out.println("----- Third Test, non-static method, same object -----"); 
    threads.clear(); 
    final Main m = new Main(); 
    for (int i = 0; i < 4; ++i) { 
     threads.add(new Thread(() -> { 
     m.m2(); 
     })); 
    } 
    for (Thread t : threads) { 
     t.start(); 
    } 
    for (Thread t : threads) { 
     try { 
     t.join(); 
     } catch (InterruptedException e) { 
     e.printStackTrace(); 
     } 
    } 
    } 

    public static synchronized void m1() { 
    System.out.println(Thread.currentThread() + ": starting."); 
    try { 
     Thread.sleep(1000); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
    System.out.println(Thread.currentThread() + ": stopping."); 
    } 

    public synchronized void m2() { 
    System.out.println(Thread.currentThread() + ": starting."); 
    try { 
     Thread.sleep(1000); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
    System.out.println(Thread.currentThread() + ": stopping."); 
    } 
} 

有關更多詳細信息,請參閱this oracle page

+0

Aaah ....我的壞......完全忘了靜態。 –

+0

@KAY_YAK,如果此答案解決了您的問題,請將其標記爲已接受。 –