package com.yixin.yxcode.apus.service.erp.contracte; import cn.hutool.core.thread.ThreadFactoryBuilder; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import static java.util.concurrent.Executors.newFixedThreadPool; /** * @author wangdongjiang */ public class PrintNum implements Runnable { private ReentrantLock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); private int num = 1; @Override public void run() { while (num <= 100) { try { lock.lock(); condition.signal(); System.out.println(Thread.currentThread().getName() + ":" + num); num++; condition.await(5, TimeUnit.SECONDS); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } } public static void main(String[] args) { ExecutorService executorService = newFixedThreadPool(2, ThreadFactoryBuilder.create().setNamePrefix("线程:").build()); PrintNum printNum = new PrintNum(); for (int i = 0; i < 2; i++) { executorService.execute(printNum); } executorService.shutdown(); } }