当前位置: 首页>后端>正文

JUC:多个Condition

JUC:多个Condition,第1张
JUC:多个Condition,第2张

public class Thread06 {

public static void main(String[] args) {

Data06 data = new Data06();

new Thread(()-> {

while (true) {

data.printA();

}

}, "A").start();

new Thread(()-> {

while (true) {

data.printB();

}

}, "B").start();

new Thread(()-> {

while (true) {

data.printC();

}

}, "C").start();

}

}

class Data06 {

Lock lock = new ReentrantLock();

Condition condition1 = lock.newCondition();

Condition condition2 = lock.newCondition();

Condition condition3 = lock.newCondition();

int number = 1; // 1A 2B 3C

public void printA() {

lock.lock();

try {

while (number != 1) {

condition1.await();

}

System.out.println(Thread.currentThread().getName() + "=>AAA");

number = 2;

condition2.signal();

} catch (Exception e) {

e.printStackTrace();

} finally {

lock.unlock();

}

}

public void printB() {

lock.lock();

try {

while (number != 2) {

condition2.await();

}

System.out.println(Thread.currentThread().getName() + "=>BBB");

number = 3;

condition3.signal();

} catch (Exception e) {

e.printStackTrace();

} finally {

lock.unlock();

}

}

public void printC() {

lock.lock();

try {

while (number != 3) {

condition3.await();

}

System.out.println(Thread.currentThread().getName() + "=>CCC");

number = 1;

condition1.signal();

} catch (Exception e) {

e.printStackTrace();

} finally {

lock.unlock();

}

}

}


https://www.xamrdz.com/backend/3ub1935373.html

相关文章: