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

本文通过具体的Java代码示例,详细介绍了线程同步机制的工作原理。演示了如何使用synchronized关键字来确保线程安全,并对比了不同实现方式的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

测试类:

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;
		}

}

这两种都可以实现


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值