2016-10-10 99 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,如果此答案解决了您的问题,请将其标记为已接受。 –