public class Task extends Thread{
private String content;
private static ReentrantLock lock = new ReentrantLock(true);
private static CyclicBarrier barrier = new CyclicBarrier(2);
public Task(String content) {
this.content = content;
}
@Override
public void run() {
while(true){
try{
barrier.await();
lock.lock();
System.out.println(content);
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
public static void main(String[] args) throws InterruptedException {
Task task1 = new Task("A");
Task task2 = new Task("B");
task1.start();
task2.start();
}
}