线程锁synchronized (this)锁住的是对象还是方法

发布日期:2025-09-27 17:16:52 分类:office365桌面应用 浏览:8042

测试类:

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;

}

}

这两种都可以实现