在 Java 中,线程间通信是通过共享内存或消息传递实现的。以下是详细的线程间通信方式及其示例代码:
1. 共享变量
线程可以通过共享变量进行通信,但需要确保线程安全。常用的方法包括:
- 使用
volatile关键字保证可见性。 - 使用
synchronized关键字保证同步。
示例代码
class SharedObject {
private volatile boolean flag = false;
public void setFlag(boolean flag) {
this.flag = flag;
}
public boolean getFlag() {
return flag;
}
}
public class SharedVariableExample {
public static void main(String[] args) {
SharedObject shared = new SharedObject();
Thread writerThread = new Thread(() -> {
try {
Thread.sleep(1000); // 模拟耗时操作
shared.setFlag(true);
System.out.println("Flag set to true by writer thread.");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread readerThread = new Thread(() -> {
while (!shared.getFlag()) {
// 等待 flag 变为 true
}
System.out.println("Flag is true, reader thread exiting.");
});
writerThread.start();
readerThread.start();
}
}
输出:
Flag set to true by writer thread.
Flag is true, reader thread exiting.
2. wait()、notify() 和 notifyAll()
这些方法用于线程间的协调,必须在 synchronized 块或方法中使用。
wait():使当前线程等待,释放锁。notify():唤醒一个等待的线程。notifyAll():唤醒所有等待的线程。
示例代码
class SharedResource {
private boolean ready = false;
public synchronized void waitForReady() throws InterruptedException {
while (!ready) {
wait(); // 等待 ready 变为 true
}
System.out.println("Resource is ready, continuing execution.");
}
public synchronized void setReady() {
this.ready = true;
notifyAll(); // 唤醒所有等待的线程
System.out.println("Resource is now ready, notifying all waiting threads.");
}
}
public class WaitNotifyExample {
public static void main(String[] args) {
SharedResource shared = new SharedResource();
Thread waitingThread = new Thread(() -> {
try {
shared.waitForReady();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread notifyingThread = new Thread(() -> {
try {
Thread.sleep(2000); // 模拟耗时操作
shared.setReady();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
waitingThread.start();
notifyingThread.start();
}
}
输出:
Resource is now ready, notifying all waiting threads.
Resource is ready, continuing execution.
3. BlockingQueue
BlockingQueue 是一个线程安全的队列,支持阻塞操作,常用于生产者-消费者模式。
示例代码
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class ProducerConsumerExample {
public static void main(String[] args) {
BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(10);
// 生产者线程
Thread producer = new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
queue.put(i); // 将数据放入队列
System.out.println("Produced: " + i);
Thread.sleep(100); // 模拟生产耗时
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
// 消费者线程
Thread consumer = new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
int value = queue.take(); // 从队列中取出数据
System.out.println("Consumed: " + value);
Thread.sleep(200); // 模拟消费耗时
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
producer.start();
consumer.start();
}
}
输出:
Produced: 0
Consumed: 0
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
...
Produced: 9
Consumed: 9
4. CountDownLatch
CountDownLatch 是一个同步工具,允许一个或多个线程等待其他线程完成操作。
示例代码
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
int numThreads = 3;
CountDownLatch latch = new CountDownLatch(numThreads);
for (int i = 0; i < numThreads; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " is working...");
try {
Thread.sleep(1000); // 模拟工作
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " finished.");
latch.countDown(); // 计数器减 1
}).start();
}
latch.await(); // 等待所有线程完成
System.out.println("All threads have finished.");
}
}
输出:
Thread-0 is working...
Thread-1 is working...
Thread-2 is working...
Thread-0 finished.
Thread-1 finished.
Thread-2 finished.
All threads have finished.
5. CyclicBarrier
CyclicBarrier 是一个同步工具,允许多个线程在某个屏障点等待,直到所有线程都到达。
示例代码
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierExample {
public static void main(String[] args) {
int numThreads = 3;
CyclicBarrier barrier = new CyclicBarrier(numThreads, () -> {
System.out.println("All threads have reached the barrier.");
});
for (int i = 0; i < numThreads; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " is working...");
try {
Thread.sleep(1000); // 模拟工作
System.out.println(Thread.currentThread().getName() + " reached the barrier.");
barrier.await(); // 等待其他线程
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}
}
输出:
Thread-0 is working...
Thread-1 is working...
Thread-2 is working...
Thread-0 reached the barrier.
Thread-1 reached the barrier.
Thread-2 reached the barrier.
All threads have reached the barrier.
总结
Java 提供了多种线程间通信的方式:
- 共享变量:通过
volatile或synchronized实现。 - wait()/notify():用于线程间的协调。
- BlockingQueue:用于生产者-消费者模式。
- CountDownLatch:等待多个线程完成。
- CyclicBarrier:多个线程在屏障点同步。
2905

被折叠的 条评论
为什么被折叠?



