字母和数字交替输出,并保证字母永远排在前面

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();
 }
}

 

你可能感兴趣的:(java,java)