在多线程的场景,如果对一个变量加锁以保证同一时间只有一个线程访问?

在多线程的场景,如果对一个变量加锁以保证同一时间只有一个线程访问?

1.synchronized

public class SynchronizedExample {
	private int counter = 0;

	// 使用 synchronized 修饰方法
	public synchronized void increment() {
		counter++;
	}
	// 使用 synchronized 修饰代码块
	public void incrementWithBlock() {
		synchronized (this) {
			counter++;
		}
	}
	public int getCounter() {
		return counter;
	}

	public static void main(String[] args) throws InterruptedException {
		SynchronizedExample example = new SynchronizedExample();
		// 创建多个线程并发执行
		Runnable task = () -> {
			for (int i = 0; i < 1000; i++) {
				example.increment(); // 或者调用 example.incrementWithBlock()
			}
		};

		Thread thread1 = new Thread(task);
		Thread thread2 = new Thread(task);

		thread1.start();
		thread2.start();
		
		// 等待线程执行完成
		thread1.join();
		thread2.join();

		System.out.println("Final counter value: " + example.getCounter()); // 输出: 2000
	}
}
		

2.reentrantlock

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockExample {
	private int counter = 0;
	private final Lock lock = new ReentrantLock(); // 创建锁对象

	public void increment() {
		lock.lock(); // 加锁
		try {
			counter++;
		}finally {
			lock.unlock(); // 释放锁
		}
	}
	public int getCounter() {
		return counter;
	}
	public static void main(String[] args) throws InterruptedException {
		ReentrantLockExample example = new ReentrantLockExample();

		// 创建多个线程并发执行
		Runnable task = () -> {
			for (int i = 0; i < 1000; i++) {
				example.increment();
			}
		};

		Thread thread1 = new Thread(task);
		Thread thread2 = new Thread(task);
		
		thread1.start();
		thread2.start();
		
		// 等待线程执行完成
		thread1.join();
		thread2.join();

		System.out.println("Final counter value: " + example.getCounter()); // 输出: 2000
}}

3.使用 AtomicInteger(无锁实现)

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerExample {
	private AtomicInteger counter = new AtomicInteger(0);

	public void increment() {
		counter.incrementAndGet(); // 原子递增
	}
	public int getCounter() {
		return counter.get();
	}
	public static void main(String[] args) throws InterruptedException {
		AtomicIntegerExample example = new AtomicIntegerExample();
	
		// 创建多个线程并发执行
		Runnable task = () -> {
			for (int i = 0; i < 1000; i++) {
				example.increment();
			}
		};
		
		Thread thread1 = new Thread(task);
		Thread thread2 = new Thread(task);
		
		thread1.start();
		thread2.start();
		
		// 等待线程执行完成
		thread1.join();
		thread2.join();
		
		System.out.println("Final counter value: " + example.getCounter()); // 输出: 2000
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

clarence.wei

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

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

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

打赏作者

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

抵扣说明:

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

余额充值