synchronized:wait和notify
lock:await和signal
package com.model.concurrent; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * 备注:多线程之间循序调用,实现A->B->C * 三个线程,要求如下: * A打印五次,B打印十次,C打印十五次 * 接着 * A打印五次,B打印十次,C打印十五次 * 来十轮 * * * */ class Print{ private int num=1; private Lock lock=new ReentrantLock(); private Condition c1=lock.newCondition(); private Condition c2=lock.newCondition(); private Condition c3=lock.newCondition(); public void print_a(){ lock.lock(); try { if (num!=1){ c1.await(); } for (int i=0;i<5;i++) { System.out.println("A\t"+i); } num++; c2.signal(); }catch (Exception e){ e.printStackTrace(); }finally { lock.unlock(); } } public void print_b(){ lock.lock(); try { if (num!=2){ c2.await(); } for (int i=0;i<10;i++) { System.out.println("B\t"+i); } num++; c3.signal(); }catch (Exception e){ e.printStackTrace(); }finally { lock.unlock(); } } public void print_c(){ lock.lock(); try { if (num!=3){ c3.await(); } for (int i=0;i<15;i++) { System.out.println("C\t"+i); } num=1; c1.signal(); }catch (Exception e){ e.printStackTrace(); }finally { lock.unlock(); } } } public class ConditionDemo { public static void main(String[] args) { Print print=new Print(); new Thread(() ->{ for (int i = 0; i < 10; i++) { print.print_a(); } },"A").start(); new Thread(() ->{ for (int i = 0; i < 10; i++) { print.print_b(); } },"B").start(); new Thread(() ->{ for (int i = 0; i < 10; i++) { print.print_c(); } },"C").start(); } }
原文:https://www.cnblogs.com/zzhAylm/p/14851356.html