// synchronized 示例代码
public class SynchronizedExample {
    private int count = 0;
    // 使用 synchronized 关键字修饰方法,确保同一时间只有一个线程可以执行该方法
    public synchronized void increment() {
        count++;
    }
    public int getCount() {
        return count;
    }
    public static void main(String[] args) throws InterruptedException {
        SynchronizedExample example = new SynchronizedExample();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                example.increment();
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                example.increment();
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Final count: " + example.getCount());
    }
}
// Lock 示例代码
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockExample {
    private int count = 0;
    private final Lock lock = new ReentrantLock();
    // 使用 Lock 对象显式地控制锁的获取和释放
    public void increment() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }
    public int getCount() {
        return count;
    }
    public static void main(String[] args) throws InterruptedException {
        LockExample example = new LockExample();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                example.increment();
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                example.increment();
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Final count: " + example.getCount());
    }
}Synchronized 示例代码:
increment 方法使用了 synchronized 关键字,确保同一时间只有一个线程可以进入该方法。main 方法中创建了两个线程 t1 和 t2,它们分别调用 increment 方法 1000 次。Lock 示例代码:
ReentrantLock 类来显式地控制锁的获取和释放。lock.lock() 获取锁,lock.unlock() 释放锁。try-finally 确保即使发生异常也能正确释放锁。main 方法中的逻辑与 synchronized 示例相同,最终输出的结果也应该是 2000。这两种方式都可以保证线程安全,但 Lock 提供了更灵活的锁机制,适合更复杂的场景。
上一篇:java lombok
下一篇:java发送http请求
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站