public class StaticSynTest extends Thread {
StaticMothod sm;
public StaticSynTest(StaticMothod sm){ this.sm = sm; } public static void main(String[] args) { StaticMothod sm1 = new StaticMothod(); StaticSynTest sst1 = new StaticSynTest(sm1); StaticSynTest sst2 = new StaticSynTest(sm1); StaticSynTest sst3 = new StaticSynTest(sm1); sst1.setName("sst1"); sst2.setName("sst2"); sst3.setName("sst3"); sst1.start(); sst2.start(); sst3.start(); } public void run(){ this.sm.b(Thread.currentThread().getName()); this.sm.b1(Thread.currentThread().getName()); StaticMothod.a(Thread.currentThread().getName()); StaticMothod.a1(Thread.currentThread().getName()); } } class StaticMothod{ public synchronized static void a(String name){ System.out.println(name+":a in"); try{ Thread.sleep(2000); System.out.println(""); } catch(InterruptedException e){ } System.out.println(name+":a out"); } public synchronized static void a1(String name){ System.out.println(name+":a1 in"); try{ Thread.sleep(2000); System.out.println(""); } catch(InterruptedException e){ } System.out.println(name+":a1 out"); } public synchronized void b(String name){ System.out.println(name+":b in"); try{ Thread.sleep(2000); System.out.println(""); } catch(InterruptedException e){ } System.out.println(name+":b out"); } public synchronized void b1(String name){ System.out.println(name+":b1 in"); try{ Thread.sleep(2000); System.out.println(""); } catch(InterruptedException e){ } System.out.println(name+":b1 out"); } }输出结果为:
sst1:b in
sst1:b out sst2:b in sst2:b out sst3:b in sst3:b out sst1:b1 in sst1:b1 out sst1:a in sst2:b1 in sst1:a out sst1:a1 in sst2:b1 out sst3:b1 in sst3:b1 out sst1:a1 out sst2:a in sst2:a out sst3:a in sst3:a out sst2:a1 in sst2:a1 out sst3:a1 in sst3:a1 out
结论:
1、当前线程调用类的同步静态方法时,其它线程可以进入该类实例的其它非静态方法,不能进入类的其它静态方法。
2、同理,当前进入同步的实例方法时,其它线程可以进入该类的静态方法,但是不能进入该类的其它非静态方法。
原因:静态方法同步是获取StaticSynTest.class锁,而实例方法获取的是该“实例对象”的锁,它们互不干涉。
转载自