不運行如下幾段代碼的狀況下你能得出輸出結果嗎? (大神就別看啦,都是很基礎的東西)
java
代碼1ide
package com.ls; public class Test { synchronized void fun1() { try { Thread.sleep(2000); } catch (InterruptedException e) { } System.out.println("fun1() invoked"); } synchronized void fun2() { System.out.println("fun2() invoked"); } public static void main(String[] args) { Test t = new Test(); Thread t1 = new MyThread("thread1", t); Thread t2 = new MyThread("thread2", t); t1.start(); t2.start(); } } class MyThread extends Thread { Test t = null; public MyThread(String name, Test t) { super(name); this.t = t; } @Override public void run() { if ("thread1".equals(Thread.currentThread().getName())) { t.fun1(); } else { t.fun2(); } } }
代碼2this
package com.ls; public class Test { synchronized void fun1() { try { this.wait(); } catch (InterruptedException e) { } System.out.println("fun1() invoked"); } synchronized void fun2() { System.out.println("fun2() invoked"); this.notify(); } public static void main(String[] args) { Test t = new Test(); Thread t1 = new MyThread("thread1", t); Thread t2 = new MyThread("thread2", t); t1.start(); t2.start(); } } class MyThread extends Thread { Test t = null; public MyThread(String name, Test t) { super(name); this.t = t; } @Override public void run() { if ("thread1".equals(Thread.currentThread().getName())) { t.fun1(); } else { t.fun2(); } } }
代碼3code
package com.ls; public class Test { synchronized static void fun1() { try { Thread.sleep(2000); } catch (InterruptedException e) { } System.out.println("fun1() invoked"); } synchronized void fun2() { System.out.println("fun2() invoked"); } public static void main(String[] args) throws Exception { Test t = new Test(); Thread t1 = new MyThread("thread1", t); Thread t2 = new MyThread("thread2", t); t1.start(); Thread.sleep(10); t2.start(); } } class MyThread extends Thread { Test t = null; public MyThread(String name, Test t) { super(name); this.t = t; } @Override public void run() { if ("thread1".equals(Thread.currentThread().getName())) { t.fun1(); } else { t.fun2(); } } }
代碼4get
package com.ls; public class Test { synchronized void fun1() { try { Thread.sleep(2000); } catch (InterruptedException e) { } System.out.println("fun1() invoked"); } void fun2() { System.out.println("fun2() invoked"); } public static void main(String[] args) { Test t = new Test(); Thread t1 = new MyThread("thread1", t); Thread t2 = new MyThread("thread2", t); t1.start(); t2.start(); } } class MyThread extends Thread { Test t = null; public MyThread(String name, Test t) { super(name); this.t = t; } @Override public void run() { if ("thread1".equals(Thread.currentThread().getName())) { t.fun1(); } else { t.fun2(); } } }