package test; import java.util.Date; import java.util.Random; public class test { public static void main(String[] args) { TicketThread thread = new TicketThread(); for (int i = 0; i < 10; i++) { new Thread(thread, "client-" + (i + 1)).start(); } } public static class TicketThread implements Runnable { private int stock = 10; private Object lock = new Object(); public void run() { while (stock > 0) { synchronized (lock) { if (stock > 0) { try { Integer processingTime = new Random().nextInt(1000); System.out.println(Thread.currentThread().getName() + ":订单处理中..."+ stock + new Date()); Thread.sleep(processingTime); System.out.println(Thread.currentThread().getName() + ":交易成功,库存余量:" + --stock + new Date()); lock.wait(12000); //释放锁,其余的线程不等待12秒,直接去打印 //Thread.sleep(12000); 锁不放,其余的线程不能打印,等待12秒出一个打印 System.out.println(Thread.currentThread().getName() + ":睡眠结束...:" + stock + new Date()); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } }