线程间通信的关键在于选择合适的机制以实现信息传递与协同操作,1. 共享变量配合synchronized或volatile可实现基础通信,但需注意线程安全;2. wait/notify/notifyall用于线程间的等待与唤醒,必须在synchronized块中使用;3. blockingqueue通过阻塞方式简化数据传递,适合生产者-消费者模型;4. countdownlatch用于一个或多个线程等待其他线程完成,计数器减至零时释放等待线程;5. cyclicbarrier用于多线程互相等待到达屏障点后继续执行,支持重复使用;6. exchanger适用于两个线程之间交换数据;7. 避免死锁需破坏占有且等待、循环等待等条件,可通过按序获取锁、使用定时锁等方式实现;8. volatile保证变量可见性和禁止指令重排序,但不保证原子性;9. 选择通信方式应根据场景综合考虑,如状态传递用volatile,阻塞等待用blockingqueue,线程同步用countdownlatch或cyclicbarrier,数据交换用exchanger,最终目标是确保线程安全、避免死锁并提升程序效率。

线程间的通信,简单来说,就是让不同的线程能够互相“说话”,传递信息,协同完成任务。Java提供了多种机制来实现这一点,但关键在于理解这些机制背后的原理,并根据实际场景选择最合适的方案。
解决方案
Java中实现线程间通信的方式有很多,常见的包括:
立即学习“Java免费学习笔记(深入)”;
共享变量: 这是最基础的方式。多个线程访问同一个变量,通过修改变量的值来传递信息。但需要注意线程安全问题,通常需要使用
synchronized
volatile
public class SharedData {
private boolean ready = false;
public synchronized void setReady(boolean ready) {
this.ready = ready;
notifyAll(); // 通知所有等待的线程
}
public synchronized boolean isReady() throws InterruptedException {
while (!ready) {
wait(); // 等待ready变为true
}
return ready;
}
}
// 线程A
public class ThreadA extends Thread {
private SharedData data;
public ThreadA(SharedData data) {
this.data = data;
}
@Override
public void run() {
// 执行一些操作后
data.setReady(true);
System.out.println("Thread A: Data is ready!");
}
}
// 线程B
public class ThreadB extends Thread {
private SharedData data;
public ThreadB(SharedData data) {
this.data = data;
}
@Override
public void run() {
try {
boolean ready = data.isReady();
System.out.println("Thread B: Data is ready? " + ready);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Main {
public static void main(String[] args) {
SharedData data = new SharedData();
ThreadA threadA = new ThreadA(data);
ThreadB threadB = new ThreadB(data);
threadB.start(); // 先启动ThreadB,让它等待
threadA.start();
}
}这里使用了
synchronized
wait/notifyAll
wait()
notifyAll()
wait()
notify()
notifyAll()
Object
synchronized
wait()
notify()
notifyAll()
BlockingQueue
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class BlockingQueueExample {
private static BlockingQueue<String> queue = new LinkedBlockingQueue<>();
public static void main(String[] args) {
new Thread(() -> {
try {
System.out.println("Producer: Producing message 1");
queue.put("Message 1");
System.out.println("Producer: Producing message 2");
queue.put("Message 2");
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
Thread.sleep(100); // 模拟消费者慢一点
System.out.println("Consumer: Consuming " + queue.take());
System.out.println("Consumer: Consuming " + queue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}BlockingQueue
wait/notify
CountDownLatch
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(3); // 计数器初始值为3
new Thread(() -> {
System.out.println("Thread 1: Doing some work...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown(); // 计数器减1
System.out.println("Thread 1: Work finished, countdown!");
}).start();
new Thread(() -> {
System.out.println("Thread 2: Doing some work...");
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown(); // 计数器减1
System.out.println("Thread 2: Work finished, countdown!");
}).start();
new Thread(() -> {
System.out.println("Thread 3: Doing some work...");
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown(); // 计数器减1
System.out.println("Thread 3: Work finished, countdown!");
}).start();
latch.await(); // 主线程等待,直到计数器变为0
System.out.println("Main thread: All threads finished their work!");
}
}CountDownLatch
CyclicBarrier
CountDownLatch
CyclicBarrier
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierExample {
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(3, () -> {
System.out.println("All threads have reached the barrier. Executing barrier action!");
});
for (int i = 0; i < 3; i++) {
final int threadId = i;
new Thread(() -> {
System.out.println("Thread " + threadId + ": Starting...");
try {
Thread.sleep((long) (Math.random() * 3000)); // 模拟不同的工作时间
System.out.println("Thread " + threadId + ": Reached the barrier, waiting for others...");
barrier.await(); // 等待其他线程到达屏障
System.out.println("Thread " + threadId + ": Continuing after the barrier...");
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}
}CyclicBarrier
Exchanger
import java.util.concurrent.Exchanger;
public class ExchangerExample {
public static void main(String[] args) {
Exchanger<String> exchanger = new Exchanger<>();
new Thread(() -> {
String data = "Data from Thread 1";
try {
System.out.println("Thread 1: Exchanging data: " + data);
String receivedData = exchanger.exchange(data);
System.out.println("Thread 1: Received data: " + receivedData);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
String data = "Data from Thread 2";
try {
System.out.println("Thread 2: Exchanging data: " + data);
String receivedData = exchanger.exchange(data);
System.out.println("Thread 2: Received data: " + receivedData);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}Exchanger
如何避免死锁?
死锁是多线程编程中常见的问题,指的是两个或多个线程互相等待对方释放资源,导致所有线程都无法继续执行。避免死锁的关键在于破坏死锁产生的条件:
因此,避免死锁的常见策略包括:
tryLock()
volatile
volatile
volatile
volatile
但是,
volatile
i++
synchronized
AtomicInteger
如何选择合适的线程通信方式?
选择合适的线程通信方式取决于具体的应用场景。
volatile
wait/notify
BlockingQueue
BlockingQueue
CountDownLatch
CyclicBarrier
Exchanger
总之,理解各种线程通信机制的原理和适用场景,并根据实际需求选择最合适的方案,是编写高效、可靠的多线程程序的关键。
以上就是java代码怎样实现线程间的通信 java代码线程协作的实用技巧的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号