Java同步块

本文详细介绍了Java中四种不同类型的同步块:实例方法、静态方法、实例方法中的同步块及静态方法中的同步块。并通过示例展示了如何使用同步机制来确保线程安全,特别是在涉及多个线程对同一实例进行操作时。

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

参考URL:Java并发性和多线程介绍

 

1.有四种不同的同步块:实例方法、静态方法、实例方法中的同步块、静态方法中的同步块

2.实例方法和静态方法同步语句的监视器对象不同。

// 实例方法
synchronized(this){
    // 监视器this为实例对象
}

// 静态方法
synchronized(MyClass.class){
    // 监视器MyClass.class为类对象,一个类只有一个类对象
}

3.Java同步实例

在下面例子中,启动了两个线程,都调用Counter类同一个实例的add方法,只能有一个线程访问该方法。

public class Counter{
    long count = 0;
    public synchronized void add(long value){// run方法同步在实例上
        this.count += value;
    }
}

public class CounterThread extends Thread{
    protected Counter counter = null;
    public CounterThread(Counter counter){
        this.counter = counter;// 两个线程引用了同一个counter,一个实例拷贝了两个引用
    }
    public void run() {
	    for(int i=0; i<10; i++){
	        counter.add(i);
	    }
    }
}

public class Example {
    public static void main(String[] args){
        Counter counter = new Counter();
    	// CounterThread的构造器引用同一个Counter实例
        Thread threadA = new CounterThread(counter);
        Thread threadB = new CounterThread(counter);
        // run方法同步在实例上,一个实例只能有一个线程
        threadA.start();
        threadB.start();
    }
}

如果调用Counter类不同实例的add方法,就不存在同步的问题,它们可以同时执行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值