实现Java多线程中的线程间通信
大家好,我是微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!
1. 线程间通信的基本概念
在线程编程中,线程间通信是指多个线程之间通过共享内存或消息传递的方式进行交互和协作。Java提供了多种机制来实现线程间通信,如共享对象、wait/notify机制、管道、并发集合等。
2. 使用wait和notify实现线程间通信
wait和notify是Java中基本的线程同步机制,用于在共享对象上进行等待和唤醒操作。以下是一个简单的例子,展示如何通过wait和notify实现线程间的基本通信。
package cn.juwatech.threadcommunication;
public class WaitNotifyExample {
public static void main(String[] args) {
Message message = new Message();
Thread producerThread = new Thread(new Producer(message));
Thread consumerThread = new Thread(new Consumer(message));
producerThread.start();
consumerThread.start();
}
static class Message {
private String content;
private boolean empty = true;
public synchronized String read() {
while (empty) {
try {
wait(); // 等待生产者线程写入内容
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
empty = true;
notifyAll(); // 唤醒其他等待线程
return content;
}
public synchronized void write(String content) {
while (!empty) {
try {
wait(); // 等待消费者线程读取内容
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
this.content = content;
empty = false;
notifyAll(); // 唤醒其他等待线程
}
}
static class Producer implements Runnable {
private final Message message;
Producer(Message message) {
this.message = message;
}
@Override
public void run() {
String[] messages = {"Message 1", "Message 2", "Message 3"};
for (String msg : messages) {
message.write(msg);
System.out.println("Produced: " + msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
static class Consumer implements Runnable {
private final Message message;
Consumer(Message message) {
this.message = message;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
String msg = message.read();
System.out.println("Consumed: " + msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
}
3. 使用Lock和Condition实现线程间通信
除了wait和notify,Java还提供了更灵活的Lock和Condition机制,可以更精确地控制线程的等待和唤醒。
package cn.juwatech.threadcommunication;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockConditionExample {
public static void main(String[] args) {
Message message = new Message();
Thread producerThread = new Thread(new Producer(message));
Thread consumerThread = new Thread(new Consumer(message));
producerThread.start();
consumerThread.start();
}
static class Message {
private String content;
private boolean empty = true;
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
public void read() {
lock.lock();
try {
while (empty) {
try {
condition.await(); // 等待生产者线程写入内容
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
empty = true;
condition.signalAll(); // 唤醒其他等待线程
System.out.println("Consumed: " + content);
} finally {
lock.unlock();
}
}
public void write(String content) {
lock.lock();
try {
while (!empty) {
try {
condition.await(); // 等待消费者线程读取内容
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
this.content = content;
empty = false;
condition.signalAll(); // 唤醒其他等待线程
System.out.println("Produced: " + content);
} finally {
lock.unlock();
}
}
}
static class Producer implements Runnable {
private final Message message;
Producer(Message message) {
this.message = message;
}
@Override
public void run() {
String[] messages = {"Message 1", "Message 2", "Message 3"};
for (String msg : messages) {
message.write(msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
static class Consumer implements Runnable {
private final Message message;
Consumer(Message message) {
this.message = message;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
message.read();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
}
4. 总结
通过本文的实例,你应该已经掌握了在Java多线程编程中实现线程间通信的基本方法,包括使用wait/notify和Lock/Condition机制。合理地应用这些机制可以有效地管理线程之间的协作,提升程序的并发处理能力。
微赚淘客系统3.0小编出品,必属精品,转载请注明出处!