10分钟学会Java多线程同步方法,快速上手线程控制
本文面向Java初学者和开发爱好者,系统讲解Java多线程同步操作方法。内容涵盖线程基础、线程安全问题、synchronized关键字、ReentrantLock锁、线程间通信、死锁避免以及实用同步操作案例。通过分步讲解和实例演示,帮助读者快速掌握多线程同步技巧,确保并发程序的稳定性和可靠性。
正文教程
一、多线程基础
线程创建方式
public class MyThread extends Thread {
public void run() {
System.out.println("线程运行中: " + Thread.currentThread().getName());
}
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
}
}
技巧:
start()启动线程,run()仅是普通方法调用
实现Runnable接口
public class MyRunnable implements Runnable {
public void run() {
System.out.println("线程运行: " + Thread.currentThread().getName());
}
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
}
}
二、线程安全问题
多线程访问共享变量可能出现数据不一致
public class Counter {
int count = 0;
public void increment() {
count++; // 非线程安全
}
}
技巧:需要同步机制保证数据安全
三、使用synchronized同步方法
class CounterSync {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
技巧:synchronized保证同一时刻只有一个线程访问方法或代码块
四、使用synchronized同步代码块
public void increment() {
synchronized(this) {
count++;
}
}
技巧:代码块粒度更小,提高性能
五、使用ReentrantLock锁
import java.util.concurrent.locks.ReentrantLock;
class CounterLock {
private int count = 0;
private final ReentrantLock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public int getCount() {
return count;
}
}
技巧:可中断锁、尝试锁,提高灵活性
六、线程间通信
wait/notify
class Data {
private int number;
private boolean available = false;
public synchronized void put(int num) throws InterruptedException {
while (available) wait();
number = num;
available = true;
notify();
}
public synchronized int get() throws InterruptedException {
while (!available) wait();
available = false;
notify();
return number;
}
}
技巧:
wait()释放锁,notify()唤醒等待线程
七、避免死锁
合理加锁顺序
多线程同时加多个锁时,保持统一顺序
使用
tryLock尝试锁
if(lock1.tryLock()) {
try {
if(lock2.tryLock()) {
try {
// 业务操作
} finally { lock2.unlock(); }
}
} finally { lock1.unlock(); }
}
八、实用技巧总结
优先使用
synchronized简化同步操作ReentrantLock适合复杂同步场景
控制锁粒度,提高并发性能
使用线程间通信协调生产者-消费者模式
注意避免死锁和资源竞争