import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadDemo {
public static void main(String[] args) {
ShareData shareData = new ShareData();
new Thread(() -> {
for (int j = 0; j < 5; j++) {
try {
shareData.threadA();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "AAA").start();
new Thread(() -> {
for (int j = 0; j < 5; j++) {
try {
shareData.threadB();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "BBB").start();
}
}
class ShareData {
int num = 1;
private Lock lock = new ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
void threadA() throws InterruptedException {
lock.lock();
while (num != 1) {
//如果num不等于1,线程A就等待
condition1.await();
}
for (int i = 0; i < 3; i++) {
System.out.println(i + "AA");
}
//通知B执行
condition2.signal();
num = 2;
lock.unlock();
}
void threadB() throws InterruptedException {
lock.lock();
while (num != 2) {
//如果num不等于2,线程B就等待
condition2.await();
}
for (int i = 0; i < 3; i++) {
System.out.println(i + "BB");
}
num = 1;
condition1.signal();
lock.unlock();
}
}
两个线程循环交替打印
最新推荐文章于 2025-03-20 22:47:40 发布
1337

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



