Java 线程之间的数据传递机制194


在多线程编程中,线程之间的数据传递是一个常见的需求。Java 提供了多种机制来实现线程间的数据传递,每种机制都有其独特的优点和缺点。本文将探讨 Java 中常用的线程间数据传递机制,并提供代码示例以说明其用法。

共享变量

共享变量是最简单的数据传递机制。它涉及多个线程访问同一内存位置。共享变量可以是类变量或实例变量。使用共享变量时,必须注意同步,以防止数据竞争和不一致。```java
public class SharedVariableExample {
private static int sharedVariable = 0;
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
sharedVariable++;
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
sharedVariable--;
}
});
();
();
try {
();
();
} catch (InterruptedException e) {
();
}
("Final value of sharedVariable: " + sharedVariable);
}
}
```

同步方法

同步方法通过在方法上添加 synchronized 关键字来实现线程安全。当一个线程进入一个同步方法时,其他线程将被阻塞,直到该线程退出该方法。这可以防止多个线程同时访问共享数据。```java
public class SynchronizedMethodExample {
private int sharedVariable = 0;
public synchronized void increment() {
sharedVariable++;
}
public synchronized void decrement() {
sharedVariable--;
}
public static void main(String[] args) {
SynchronizedMethodExample example = new SynchronizedMethodExample();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
();
}
});
();
();
try {
();
();
} catch (InterruptedException e) {
();
}
("Final value of sharedVariable: " + );
}
}
```

锁是一种更细粒度的同步机制。可以使用 ReentrantLock 或 synchronized 块来创建锁。锁允许线程在进入关键部分之前获取锁,并在退出关键部分后释放锁。这可以防止多个线程同时访问共享数据。```java
public class LockExample {
private int sharedVariable = 0;
private Lock lock = new ReentrantLock();
public void increment() {
();
try {
sharedVariable++;
} finally {
();
}
}
public void decrement() {
();
try {
sharedVariable--;
} finally {
();
}
}
public static void main(String[] args) {
LockExample example = new LockExample();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
();
}
});
();
();
try {
();
();
} catch (InterruptedException e) {
();
}
("Final value of sharedVariable: " + );
}
}
```

阻塞队列

阻塞队列是一个线程安全的队列,允许线程在队列为空时阻塞,并在队列非空时解除阻塞。可以使用 BlockingQueue 实现阻塞队列。```java
import ;
import ;
public class BlockingQueueExample {
private BlockingQueue queue = new LinkedBlockingQueue();
public void produce() {
for (int i = 0; i < 1000; i++) {
try {
(i);
} catch (InterruptedException e) {
();
}
}
}
public void consume() {
while (!()) {
try {
Integer item = ();
("Consuming item: " + item);
} catch (InterruptedException e) {
();
}
}
}
public static void main(String[] args) {
BlockingQueueExample example = new BlockingQueueExample();
Thread t1 = new Thread(() -> {
();
});
Thread t2 = new Thread(() -> {
();
});
();
();
try {
();
();
} catch (InterruptedException e) {
();
}
}
}
```

选择合适的机制

选择合适的线程间数据传递机制取决于应用程序的具体需求。对于简单的数据传递,共享变量可能是合适的。对于需要同步的数据访问,同步方法或锁更为合适。对于需要处理并发数据,阻塞队列是更合适的选择。

此外,还可以使用其他机制来传递数据,例如管道、信号量和事件。这些机制适用于更高级的场景,例如进程间通信。

2024-12-09


上一篇:Java 方法共享:提升代码可重用性

下一篇:Java 天气预报程序:利用 OpenWeatherMap API 获取实时天气数据