以上代码给出测试demo
时间: 2024-02-18 08:21:04 浏览: 72
以下是修正后的代码示例,可以测试线程按顺序输出字母"A"、"B"、"C":
```java
package com.company.calcul;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Thread1 {
public static void main(String[] args) {
ReentrantLock reentrantLock = new ReentrantLock();
Condition condition1 = reentrantLock.newCondition();
Condition condition2 = reentrantLock.newCondition();
Condition condition3 = reentrantLock.newCondition();
Thread threadA = new Thread(() -> {
reentrantLock.lock();
try {
condition1.await();
System.out.println("A");
condition2.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
reentrantLock.unlock();
}
});
Thread threadB = new Thread(() -> {
reentrantLock.lock();
try {
condition2.await();
System.out.println("B");
condition3.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
reentrantLock.unlock();
}
});
Thread threadC = new Thread(() -> {
reentrantLock.lock();
try {
condition3.await();
System.out.println("C");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
reentrantLock.unlock();
}
});
reentrantLock.lock();
try {
threadA.start();
threadB.start();
threadC.start();
condition1.signal();
} finally {
reentrantLock.unlock();
}
}
}
```
在这个示例中,线程A、B、C会按顺序输出字母"A"、"B"、"C"。通过使用ReentrantLock和Condition来控制线程的等待和唤醒,以及保证线程的顺序执行。在主线程中,先获取锁,然后启动线程A、B、C,并调用condition1.signal()来唤醒线程A开始执行。在各个线程的逻辑中,先获取锁,然后进入等待状态,直到收到相应的信号并被唤醒后,打印相应的字母,并唤醒下一个线程。最后,释放锁以保证其他线程能够获取锁并执行。
阅读全文