字母和數字交替輸出,並保證字母永遠排在前面

演員¹²¹³⁸發表於2020-10-10
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest {
 static ReentrantLock lock = new ReentrantLock();
 static Condition cond1 = lock.newCondition();
 static Condition cond2 = lock.newCondition();

 public static void main(String[] args) {
  final char[] str1 = "1234567".toCharArray();
  final char[] str2 = "ABCDEFG".toCharArray();
  final CountDownLatch countdown = new CountDownLatch(1);
  new Thread(new Runnable() {
   @Override
   public void run() {
    try {
     countdown.await();
     lock.lock();
     for (char c : str1) {
      System.out.print(c);
      cond2.signal();
      cond1.await();
     }
     cond2.signal();
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
    lock.unlock();
   }
  }, "t1").start();
  new Thread(new Runnable() {
   @Override
   public void run() {
    try {
     lock.lock();
     for (char c : str2) {
      System.out.print(c);
      cond1.signal();
      countdown.countDown();
      cond2.await();
     }
     cond1.signal();
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
    lock.unlock();
   }
  }, "t2").start();
 }
}

 

相關文章