售票
作者:互联网
public static void main(String[] args) { Ticket t =new Ticket(50); Thread t1 = new Thread(t,"科学一道"); Thread t2 = new Thread(t,"科学二道"); Thread t3 = new Thread(t,"科学三道"); Thread t4 = new Thread(t,"科学四道"); t1.start();t2.start();t3.start();t4.start(); }
public class Ticket implements Runnable{ //设置默认票数,不设置就是100 private int num = 100; public Ticket(int num){//定义公共Ticket类 this.num=num; } public void run() { Random rand = new Random(); //售票内容 while (true){ synchronized (this) { if (num > 0) { int n=rand.nextInt(5)+1; n= Math.min(n, num); // n=n<=num?n:num; System.out.printf("[%s]售出%d张票,剩余%d张票 %n", Thread.currentThread().getName(), n,num-=n); } else { System.out.printf("%n [%s] 票已售完,停止售票", Thread.currentThread().getName()); break; } } try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } }
标签:售票,Thread,start,num,new,Ticket,public 来源: https://www.cnblogs.com/Gu1015/p/14349461.html