1. 前序
在多线程编程中,线程同步是确保数据一致性和防止竞态条件的关键。java 提供了多种用于线程同步的机制,以解决不同场景下的线程竞争问题。无论是最基本的 synchronized 关键字,还是更灵活的 reentrantlock、reentrantreadwritelock,它们都为开发者提供了不同级别的锁和控制。
本文将逐一介绍 java 中常见的同步机制,涵盖了 synchronized、reentrantlock、atomic 类等,同时给出每种机制的示例代码和适用场景,帮助你更好地理解并应用这些同步机制。
2.synchronized
2.1synchronized 关键字
- 描述:java 中最基础的同步机制就是
synchronized 关键字,它可以用于方法或代码块,确保同一时刻只有一个线程可以访问共享资源。 - 示例代码:
/**
* 示例类,演示如何使用 synchronized 方法进行线程同步
*/
public class synchronizedmethodexample {
/** 共享计数器 */
private int counter = 0;
/**
* 同步递增计数器的方法,确保同一时刻只有一个线程可以执行
*/
public synchronized void increment() {
// 递增计数器
counter++;
// 输出当前线程和计数器的值
system.out.println(thread.currentthread().getname() + " - counter: " + counter);
}
/**
* 主程序入口,创建多个线程并运行
* @param args 默认参数
*/
public static void main(string[] args) {
synchronizedmethodexample example = new synchronizedmethodexample();
// 线程任务,调用 increment 方法
runnable task = example::increment;
// 创建两个线程
thread t1 = new thread(task, "thread 1");
thread t2 = new thread(task, "thread 2");
// 启动线程
t1.start();
t2.start();
}
}
2.2 使用synchronized 代码块
- 描述:相比于
synchronized 方法,synchronized 代码块允许更细粒度地控制同步范围。可以指定特定的代码块进行同步,而不是整个方法,这样可以减少锁的竞争,提高效率。 - 示例代码:
/**
* 示例类,演示如何使用 synchronized 代码块进行线程同步
*/
public class synchronizedblockexample {
/** 共享计数器 */
private int counter = 0;
/** 自定义锁对象 */
private final object lock = new object();
/**
* 同步递增计数器的方法,只锁定代码块
*/
public void increment() {
// 使用 synchronized 代码块确保锁定的粒度更小
synchronized (lock) {
counter++;
system.out.println(thread.currentthread().getname() + " - counter: " + counter);
}
}
/**
* 主程序入口,创建多个线程并运行
* @param args 默认参数
*/
public static void main(string[] args) {
synchronizedblockexample example = new synchronizedblockexample();
runnable task = example::increment;
thread t1 = new thread(task, "thread 1");
thread t2 = new thread(task, "thread 2");
t1.start();
t2.start();
}
}
3.reentrantlock
- 描述:
reentrantlock 是lock 接口的一个常用实现,它提供了更灵活的锁定机制,允许手动加锁和解锁。 - 示例代码:
import java.util.concurrent.locks.lock;
import java.util.concurrent.locks.reentrantlock;
/**
* 示例类,演示如何使用 reentrantlock 进行线程同步
*/
public class lockexample {
/** 共享计数器 */
private int counter = 0;
/** reentrantlock 实例 */
private final lock lock = new reentrantlock();
/**
* 同步递增计数器的方法,手动加锁和解锁
*/
public void increment() {
// 获取锁
lock.lock();
try {
// 递增计数器
counter++;
// 输出当前线程和计数器的值
system.out.println(thread.currentthread().getname() + " - counter: " + counter);
} finally {
// 确保锁在最后被释放
lock.unlock();
}
}
/**
* 主程序入口,创建多个线程并运行
* @param args 默认参数
*/
public static void main(string[] args) {
lockexample example = new lockexample();
runnable task = example::increment;
thread t1 = new thread(task, "thread 1");
thread t2 = new thread(task, "thread 2");
t1.start();
t2.start();
}
}
4.reentrantreadwritelock
- 描述:
reentrantreadwritelock 提供了读写锁机制,可以让多个线程并发读取,但在写入时只有一个线程可以操作。这样可以提高在读多写少场景下的性能。 - 示例代码:
import java.util.concurrent.locks.reentrantreadwritelock;
/**
* 示例类,演示如何使用 reentrantreadwritelock 进行线程同步
*/
public class readwritelockexample {
/** 共享计数器 */
private int counter = 0;
/** reentrantreadwritelock 实例 */
private final reentrantreadwritelock lock = new reentrantreadwritelock();
/**
* 获取写锁并递增计数器
*/
public void increment() {
// 获取写锁
lock.writelock().lock();
try {
// 递增计数器
counter++;
system.out.println(thread.currentthread().getname() + " - write counter: " + counter);
} finally {
// 释放写锁
lock.writelock().unlock();
}
}
/**
* 获取读锁并读取计数器
* @return 计数器值
*/
public int getcounter() {
// 获取读锁
lock.readlock().lock();
try {
system.out.println(thread.currentthread().getname() + " - read counter: " + counter);
return counter;
} finally {
// 释放读锁
lock.readlock().unlock();
}
}
/**
* 主程序入口,创建多个线程并运行
* @param args 默认参数
*/
public static void main(string[] args) {
readwritelockexample example = new readwritelockexample();
runnable writetask = example::increment;
runnable readtask = example::getcounter;
thread t1 = new thread(writetask, "writer thread");
thread t2 = new thread(readtask, "reader thread");
t1.start();
t2.start();
}
}
5.atomic 类
- 描述:
atomic 类位于java.util.concurrent.atomic 包内,提供了常见的原子操作类(如atomicinteger),用于在无锁的情况下对单一变量进行线程安全的操作。 - 示例代码:
import java.util.concurrent.atomic.atomicinteger;
/**
* 示例类,演示如何使用 atomicinteger 进行线程同步
*/
public class atomicexample {
/** 线程安全的 atomicinteger */
private atomicinteger counter = new atomicinteger(0);
/**
* 原子性递增计数器的方法
*/
public void increment() {
// 原子递增
int newvalue = counter.incrementandget();
system.out.println(thread.currentthread().getname() + " - counter: " + newvalue);
}
/**
* 主程序入口,创建多个线程并运行
* @param args 默认参数
*/
public static void main(string[] args) {
atomicexample example = new atomicexample();
runnable task = example::increment;
thread t1 = new thread(task, "thread 1");
thread t2 = new thread(task, "thread 2");
t1.start();
t2.start();
}
}
6.cyclicbarrier
- 描述:
cyclicbarrier 是一种允许一组线程相互等待的同步机制,直到所有线程都到达某个共同的屏障点时,才能继续执行。它支持重用,即可以被多次使用。 - 示例代码:
import java.util.concurrent.brokenbarrierexception;
import java.util.concurrent.cyclicbarrier;
/**
* 示例类,演示如何使用 cyclicbarrier 实现线程同步
*/
public class cyclicbarrierexample {
/** cyclicbarrier 实例,等待 3 个线程 */
private final cyclicbarrier barrier = new cyclicbarrier(3, () -> {
// 所有线程到达屏障后执行的操作
system.out.println("all threads have reached the barrier. barrier action executed.");
});
/**
* 线程任务,等待屏障点并继续执行
*/
public void performtask() {
system.out.println(thread.currentthread().getname() + " is waiting at the barrier");
try {
// 等待其他线程到达屏障点
barrier.await();
} catch (interruptedexception | brokenbarrierexception e) {
e.printstacktrace();
}
system.out.println(thread.currentthread().getname() + " has crossed the barrier");
}
/**
* 主程序入口,创建多个线程并运行
* @param args 默认参数
*/
public static void main(string[] args) {
cyclicbarrierexample example = new cyclicbarrierexample();
thread t1 = new thread(example::performtask, "thread 1");
thread t2 = new thread(example::performtask, "thread 2");
thread t3 = new thread(example::performtask, "thread 3");
t1.start();
t2.start();
t3.start();
}
}
7.object 的wait() 和notify() 方法
- 描述:
object 类的wait()、notify() 和notifyall() 方法允许线程在某个条件下进行等待和唤醒。与synchronized 搭配使用,可以实现类似于信号量的功能。 - 示例代码:
/**
* 示例类,演示如何使用 wait() 和 notify() 进行线程同步
*/
public class waitnotifyexample {
/** 自定义锁对象 */
private final object lock = new object();
/** 标志位,表示是否已经生产了数据 */
private boolean isproduced = false;
/**
* 生产者方法,等待消费者消费后生产新数据
* @throws interruptedexception 当线程被中断时抛出异常
*/
public void produce() throws interruptedexception {
synchronized (lock) {
// 如果已经生产了数据,等待消费者消费
while (isproduced) {
lock.wait();
}
// 生产数据
system.out.println(thread.currentthread().getname() + " produced data.");
isproduced = true;
// 通知消费者可以消费数据了
lock.notify();
}
}
/**
* 消费者方法,等待生产者生产数据并进行消费
* @throws interruptedexception 当线程被中断时抛出异常
*/
public void consume() throws interruptedexception {
synchronized (lock) {
// 如果还没有生产数据,等待生产者生产
while (!isproduced) {
lock.wait();
}
// 消费数据
system.out.println(thread.currentthread().getname() + " consumed data.");
isproduced = false;
// 通知生产者可以继续生产数据了
lock.notify();
}
}
/**
* 主程序入口,创建生产者和消费者线程并运行
* @param args 默认参数
*/
public static void main(string[] args) {
waitnotifyexample example = new waitnotifyexample();
// 创建生产者线程
thread producer = new thread(() -> {
try {
for (int i = 0; i < 5; i++) {
example.produce();
}
} catch (interruptedexception e) {
e.printstacktrace();
}
}, "producer");
// 创建消费者线程
thread consumer = new thread(() -> {
try {
for (int i = 0; i < 5; i++) {
example.consume();
}
} catch (interruptedexception e) {
e.printstacktrace();
}
}, "consumer");
producer.start();
consumer.start();
}
}
8. 总结
java 提供了多种用于线程同步的机制,包括 synchronized、reentrantlock、reentrantreadwritelock、atomic 类、cyclicbarrier 以及 object 的 wait()/notify()。每种方式都有其适用场景和优缺点。对于简单的同步需求,synchronized 是一种直接而有效的选择;对于复杂的并发控制,lock 提供了更灵活的锁机制;而 wait() 和 notify() 可以实现线程之间的协调工作。
到此这篇关于java 中使用同步线程的多种实现方式的文章就介绍到这了,更多相关java 同步线程内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论