线程安全与同步控制的深度解析

在 Java 开发中,多线程是提升程序性能的关键技术,但若处理不当,也会埋下诸多隐患,尤其是线程安全问题。

一、线程的创建与启动

最基础的两种方式是继承Thread类和实现Runnable接口。继承 Thread 类时,重写 run() 方法定义线程任务,创建实例后调用 start() 方法启动。实现 Runnable 接口则将任务逻辑封装在 run() 中,再传入 Thread 构造函数。后者更常用,因为它能让类继承其他类,符合 Java 的单一继承特性。

// 实现 Runnable 接口方式
class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("任务执行:" + Thread.currentThread().getName());
    }
}
// 使用
MyRunnable mr = new MyRunnable();
Thread thread = new Thread(mr, "线程1");
thread.start();

二、线程安全问题

多个线程同时访问共享资源时,会引发数据不一致。例如,一个简单的计数器类:

class Counter {
    private int count = 0;
    public void increment() {
        count++;
    }
    public int getCount() {
        return count;
    }
}

当多个线程调用 increment() 时,count 的值可能小于实际线程调用次数总和。因为 count++ 实际上是读取、加 1、写回三个操作,线程可能在读取后被切换,导致其他线程覆盖更新。

三、同步控制:synchronized 关键字

synchronized 可用于方法或代码块,确保同一时间只有一个线程能执行同步代码。修饰实例方法时,锁是对象实例;修饰静态方法时,锁是类的 Class 对象。代码块则需指定锁对象。

class Counter {
    private int count = 0;
    public synchronized void increment() {
        count++;
    }
    public synchronized int getCount() {
        return count;
    }
}

四、锁机制与性能考量

synchronized 通过对象头的锁标志位实现,状态从无锁到偏向锁、轻量级锁、重量级锁升级。虽能保证线程安全,但过度使用会降低并发性能。

可优先借助AtomicInteger等原子类替代同步代码块:

import java.util.concurrent.atomic.AtomicInteger;
class Counter {
    private AtomicInteger count = new AtomicInteger(0);
    public void increment() {
        count.incrementAndGet();
    }
    public int getCount() {
        return count.get();
    }
}

原子类基于 CAS(Compare-And-Swap)算法,利用处理器的原子指令保障线程安全,性能更优。

五、线程间通信:wait()与notify()、notifyAll()

线程间通信可通过 synchronized 配合wait()notify()notifyAll()实现。wait()使线程释放锁并进入等待状态,直到其他线程调用notify()唤醒。需在同步代码块中使用。

public class ThreadCommunication {
    private boolean flag = false;
    public synchronized void producer() {
        if (flag) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 生产逻辑
        System.out.println("生产完成");
        flag = true;
        notify();
    }
    public synchronized void consumer() {
        if (!flag) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 消费逻辑
        System.out.println("消费完成");
        flag = false;
        notify();
    }
}

在多线程环境下,合理运用这些机制能有效提升程序的执行效率,同时保障数据的完整性和一致性。深入理解多线程的原理与技巧,是每个 Java 开发者进阶的必经之路。

posted @ 2025-07-24 11:43  kang_ms  阅读(19)  评论(0)    收藏  举报