在Java中,线程间的通信主要涉及到线程间的数据交换和协调。以下是几种常见的线程间通信方式:
-
共享对象:
线程可以通过共享对象的实例变量或方法参数来进行通信。这种方式需要特别注意线程安全,通常需要同步代码块或使用锁来避免并发问题。public class SharedObject { private int sharedValue; public void setValue(int value) { // 线程安全写入 synchronized (this) { sharedValue = value; } } public int getValue() { // 线程安全读取 synchronized (this) { return sharedValue; } } }
-
wait() 和 notify()/notifyAll():
Java线程有wait()
、notify()
和notifyAll()
方法,它们可以用来在线程间进行阻塞和唤醒操作,实现线程间的协调。public class Communication { private boolean ready = false; public synchronized void waitForSignal() throws InterruptedException { while (!ready) { wait(); // 等待信号 } // 执行后续操作 } public synchronized void sendSignal() { ready = true