Java线程如何通讯
Java线程通讯的方法
Java线程通讯主要通过共享内存和消息传递两种方式实现。以下是常见的线程通讯方法:
共享变量
使用共享变量是最基础的线程通讯方式。多个线程可以访问同一个对象的成员变量或静态变量。
public class SharedVariableExample {
private static boolean flag = false;
public static void main(String[] args) {
new Thread(() -> {
while (!flag) {
// 等待flag变为true
}
System.out.println("Flag is now true");
}).start();
new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
flag = true;
System.out.println("Flag set to true");
}).start();
}
}
wait()/notify()/notifyAll()
这些是Object类的方法,必须在同步块或同步方法中使用。
public class WaitNotifyExample {
private final Object lock = new Object();
public void doWait() throws InterruptedException {
synchronized (lock) {
System.out.println("Waiting...");
lock.wait();
System.out.println("Resumed");
}
}
public void doNotify() {
synchronized (lock) {
System.out.println("Notifying...");
lock.notify();
}
}
}
BlockingQueue
BlockingQueue接口提供了线程安全的队列实现,支持阻塞操作。
public class BlockingQueueExample {
private final BlockingQueue<String> queue = new ArrayBlockingQueue<>(10);
public void producer() throws InterruptedException {
queue.put("Message");
}
public void consumer() throws InterruptedException {
String message = queue.take();
}
}
CountDownLatch
允许一个或多个线程等待,直到在其他线程中执行的一组操作完成。
public class CountDownLatchExample {
private final CountDownLatch latch = new CountDownLatch(3);
public void worker() {
// 工作代码
latch.countDown();
}
public void await() throws InterruptedException {
latch.await();
System.out.println("All workers completed");
}
}
CyclicBarrier
允许一组线程互相等待,直到到达某个公共屏障点。
public class CyclicBarrierExample {
private final CyclicBarrier barrier = new CyclicBarrier(3);
public void worker() throws BrokenBarrierException, InterruptedException {
// 工作代码
barrier.await();
}
}
Semaphore
控制同时访问特定资源的线程数量。
public class SemaphoreExample {
private final Semaphore semaphore = new Semaphore(3);
public void accessResource() throws InterruptedException {
semaphore.acquire();
try {
// 访问资源
} finally {
semaphore.release();
}
}
}
Exchanger
允许两个线程在集合点交换对象。
public class ExchangerExample {
private final Exchanger<String> exchanger = new Exchanger<>();
public void threadA() throws InterruptedException {
String received = exchanger.exchange("Data from A");
}
public void threadB() throws InterruptedException {
String received = exchanger.exchange("Data from B");
}
}
PipedInputStream/PipedOutputStream
提供线程间的管道通讯。
public class PipedStreamExample {
private final PipedInputStream in = new PipedInputStream();
private final PipedOutputStream out = new PipedOutputStream();
public PipedStreamExample() throws IOException {
in.connect(out);
}
public void writer() throws IOException {
out.write("Hello".getBytes());
}
public void reader() throws IOException {
byte[] buffer = new byte[1024];
int len = in.read(buffer);
String message = new String(buffer, 0, len);
}
}
选择哪种线程通讯方式取决于具体应用场景。共享变量适合简单场景,wait/notify适合条件等待,BlockingQueue适合生产者消费者模式,CountDownLatch适合一次性等待,CyclicBarrier适合可重用屏障,Semaphore适合资源池管理,Exchanger适合双向交换,管道流适合字节流通讯。







