题目:有三个线程,名字为A,B,C,现在需要将它们的名字有序的打印在控制台上,顺序为ABCABC…
思路:
因为要控制某个线程的执行顺序,所以采用lock+condition+ewait+signalAll的方式
执行线程方法的类:
class ABC {
private int num = 1;
Lock lock = new ReentrantLock();
// 每一个Condition控制一个线程,让它们有序的执行
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
Condition condition3 = lock.newCondition();
public void lockA(){
lock.lock();
try {
if(num!=1){
try {
condition1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName());
num = 2;
condition2.signalAll();
} finally {
lock.unlock();
}
}
public void lockB(){
lock.lock();
try {
if(num!=2){
try {
condition2.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName());
num = 3;
condition3.signalAll();
} finally {
lock.unlock();
}
}
public void lockC(){
lock.lock();
try {
if(num!=3){
try {
condition3.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName());
num = 1;
condition1.signalAll();
}finally {
lock.unlock();
}
}
}
线程类:
class JymTestDemo implements Runnable{
private ABC abc = new ABC();
public void run() {
if(Thread.currentThread().getName().equals("A")){
for(int i =0;i<10;i++){
abc.lockA();
}
}
else if (Thread.currentThread().getName().equals("B")){
for(int i =0;i<10;i++){
abc.lockB();
}
}
else if (Thread.currentThread().getName().equals("C")){
for(int i =0;i<10;i++){
abc.lockC();
}
}
}
}
测试方法:
public class JymTest {
public static void main(String[] args) {
JymTestDemo jymTestDemo = new JymTestDemo();
new Thread(jymTestDemo,"A").start();
new Thread(jymTestDemo,"B").start();
new Thread(jymTestDemo,"C").start();
}
}
执行结果:
学习年限不足,知识过浅,说的不对请见谅。
世界上有10种人,一种是懂二进制的,一种是不懂二进制的。
来源:CSDN
作者:jym12138
链接:https://blog.csdn.net/weixin_43326401/article/details/104107636