在 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
可用于方法或代码块,确保同一时间只有一个线程能执行同步代码。修饰实例方法时,锁是对象实例;修饰静态方法时,锁是类的 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)算法,利用处理器的原子指令保障线程安全,性能更优。
线程间通信可通过 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 开发者进阶的必经之路。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。