import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ConditionCommunicationTest {
public static void main(String[] args) {
final Business business = new Business();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=1;i<=50;i++) {
business.sub(i);
}
}
}).start();
for(int i=1;i<=50;i++) {
business.main(i);
}
}
static class Business {
//synchronized 用 lock替代
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
private boolean bShouldSub = true;//子线程
//处理子线程
public void sub(int i) {
lock.lock();
try {
//如果不是子线程
while(!bShouldSub) {
try {
condition.await();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
for(int j=1;j<=10;j++) {
System.out.println("sub thread sequence of "+j + " loop of "+i);
}
bShouldSub = false;
condition.signal();
} finally {
lock.unlock();
}
}
//处理子线程
public synchronized void main(int i) {
lock.lock();
try {
//如果是子线程,主线程等待
while(bShouldSub) {
try {
condition.await();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
for(int j=1;j<=10;j++) {
System.out.println("main thread sequence of "+j + " loop of "+i);
}
bShouldSub = true;
condition.signal();
} finally {
lock.unlock();
}
}
}
}
/*static class Business {
private boolean bShouldSub = true;//子线程
//处理子线程
public synchronized void sub(int i) {
//如果不是子线程
while(!bShouldSub) {
try {
this.wait();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
for(int j=1;j<=10;j++) {
System.out.println("sub thread sequence of "+j + " loop of "+i);
}
bShouldSub = false;
this.notify();
}
//处理子线程
public synchronized void main(int i) {
//如果是子线程,主线程等待
while(bShouldSub) {
try {
this.wait();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
for(int j=1;j<=10;j++) {
System.out.println("main thread sequence of "+j + " loop of "+i);
}
bShouldSub = true;
this.notify();
}
}
}
*/java 之 Condition 线程间通信
最新推荐文章于 2025-12-07 21:20:15 发布
本文介绍了一个使用Java实现的线程间通信案例,通过ReentrantLock和Condition机制来控制两个线程之间的交互顺序,确保了主线程和子线程能够按照预设的顺序交替执行。
部署运行你感兴趣的模型镜像
您可能感兴趣的与本文相关的镜像
Llama Factory
模型微调
LLama-Factory
LLaMA Factory 是一个简单易用且高效的大型语言模型(Large Language Model)训练与微调平台。通过 LLaMA Factory,可以在无需编写任何代码的前提下,在本地完成上百种预训练模型的微调
1163

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



