執行緒鎖synchronized (this)鎖住的是物件還是方法
阿新 • • 發佈:2019-01-30
測試類:
package com.koow.kkwwo.test;
public class MyRunnable extends Thread {
public static void main(String[] args) {
Thread ta = new MyRunnable();
Thread tb = new MyRunnable();
ta.start();
tb.start();
}
public void run() {
Foo f = new Foo();
f.getX();
}
}
package com.koow.kkwwo.test; public class Foo { public int getX() { synchronized (this) { System.out.println("開始"); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("結束"); } return 0; } }
執行以上程式碼會發現執行緒鎖並沒有起作用
原因MyRunnable中run方法new新的物件
修改MyRunnable類,修改為
package com.koow.kkwwo.test; public class MyRunnable extends Thread { Foo f=null; public MyRunnable(Foo f){ this.f=f; } public static void main(String[] args) { Foo f = new Foo(); Thread ta = new MyRunnable(f); Thread tb = new MyRunnable(f); ta.start(); tb.start(); } public void run() { f.getX(); } }
再次執行,會發現執行緒鎖起作用,由此得出synchronized (this)鎖住的是物件
如果想鎖住方法,如下
package com.koow.kkwwo.test; public class Foo { public static synchronized int getX() { System.out.println("開始"); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("結束"); return 0; } }
package com.koow.kkwwo.test;
public class MyRunnable extends Thread {
public static void main(String[] args) {
Thread ta = new MyRunnable();
Thread tb = new MyRunnable();
ta.start();
tb.start();
}
public void run() {
Foo f = new Foo();
f.getX();
}
}
或者
package com.koow.kkwwo.test;
public class Foo {
public int getX() {
synchronized (Foo.class) {
System.out.println("開始");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("結束");
}
return 0;
}
}
這兩種都可以實現