java中的线程同步实现法二(Synchronized 程序段)

本文通过实例演示了如何使用synchronized关键字对对象进行同步,确保同一时间只有一个线程能访问特定代码块,有效避免了多线程环境下的数据竞争。

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

一.  简要说明:

     除了对方法进行Synchronized以便实现线程的同步之外,还可以对对象进行Synchronized的修饰,这种方式称为Synchronized程序段。此时,同一个对象的程序段一次只允许一个线程使用它。

二.  例子:

public class ThreadSyncObjTest implements Runnable {
private String str = new String();
private Integer delay = new Integer(1);
public static void main(String args[]) {
ThreadSyncObjTest r = new ThreadSyncObjTest();
Thread t;
for (int i=0; i<=2; i++) {
t = new Thread(r);
t.start();
}

System.out.println("end main");
}

public void run(){
for (int i = 0; i<=2; i++) {
//synchronized(System.out) {
//synchronized(str) { 
synchronized(delay) {  // 不能用基本类型
System.out.println(Thread.currentThread().getName());
System.out.println("count: "+ i);
}
}

}
}


三. 测试结果:
/*
Thread-0
count: 0
Thread-0
count: 1
Thread-0
count: 2
Thread-2
count: 0
Thread-2
count: 1
Thread-2
count: 2
end main
Thread-1
count: 0
Thread-1
count: 1
Thread-1
count: 2
*/

四.  说明:

1.  注意 end main的打印位置,由于这个线程是用户线程,所以,即使主程序结束,这个线程也可能没有结束。这在前前篇已经有详细的说明与举例。

2.  每个线程的两个打印语句总是两两显示在一起,没有出现混乱的现象。

3. synchronized后面括号中的不能是基本数据类型,必须是对象,当然,也可以是this。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liranke

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值