public class testThread {

   public static void main(String[] args) {

      ReentrantLock lock=new ReentrantLock();
      Condition one =lock.newCondition();
      Condition two=lock.newCondition();
      //第一个线程,从1开始
      new Thread(new Runnable() {
         @Override
         public void run() {
            int i = 1;
            while (i<=20){
               lock.lock();
               System.out.print("\nthread--1----:"+i);
               try {
               //如果另一个线程等待,则唤醒对方之后,自己等待
                  two.signalAll();
                  one.await();
                  i=i+2;
               } catch (InterruptedException e) {
                  e.printStackTrace();
               }
               finally {
                  lock.unlock();
               }
            }
         }
      }).start();
      new Thread(new Runnable() {
         @Override
         public void run() {
            int i = 2;
            while (i<=20){
               lock.lock();
               System.out.print("\nthread--2----:"+i);
               try {
               //如果另一个线程等待,则唤醒对方之后,自己等待
                  one.signalAll();
                  two.await();
                  i=i+2;
               } catch (InterruptedException e) {
                  e.printStackTrace();
               } finally {
                  lock.unlock();
               }
            }
         }
      }).start();
   }
}

使用条件锁最重要的是,自己等待之前,一定要唤醒其他线程,并且记住finally要释放锁。


Lavender
196 声望59 粉丝

喜欢开发,就酱紫~