文
章
目
录
章
目
录
本文主要讲解Java并发编程:线程间定制化通信的相关内容,我们一起来学习下。
案例任务
我们需要启动三个线程,按照如下要求:
1)AA打印5次,BB打印10次,CC打印15次
2)进行10轮
逻辑实现
代码实现
其实代码写起来也没什么特别的,就是condition.signal()可以唤醒指定的线程。看代码就知道怎么写了,不是以参数的方式来写的哦
public class ThreadDemo3 {
public static void main(String[] args) {
Share3 share3 = new Share3();
new Thread(()->{
for(int i = 0; i < 10; i++) {
try{
share3.printAA();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "AA").start();
new Thread(()->{
for(int i = 0; i < 10; i++) {
try{
share3.printBB();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "BB").start();
new Thread(()->{
for(int i = 0; i < 10; i++) {
try{
share3.printCC();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "CC").start();
}
}
class Share3 {
private int flag = 1;
private Lock lock = new ReentrantLock();
private Condition condition1 = lock.newCondition();
private Condition condition2 = lock.newCondition();
private Condition condition3 = lock.newCondition();
public void printAA() throws InterruptedException {
lock.lock();
try {
while(flag != 1) {
condition1.await();
}
for(int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName());
}
flag = 2;
condition2.signal();
}
finally {
lock.unlock();
}
}
public void printBB() throws InterruptedException {
lock.lock();
try {
while(flag != 2) {
condition2.await();
}
for(int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName());
}
flag = 3;
condition3.signal();
}
finally {
lock.unlock();
}
}
public void printCC() throws InterruptedException {
lock.lock();
try {
while(flag != 3) {
condition3.await();
}
for(int i = 0; i < 15; i++) {
System.out.println(Thread.currentThread().getName());
}
flag = 1;
condition1.signal();
}
finally {
lock.unlock();
}
}
}
以上就是Java并发编程:线程间定制化通信的全部内容,你学会了吗,希望对你有帮助,学习愉快哦!