package Run; class Ticket implements Runnable{ private int tickets = 100; public int total = 0; Object obj = new Object(); public void sell() { while ( true ) { synchronized ( obj ) { if ( tickets > 0) { System.out.println(Thread.currentThread().getName() + "..." + tickets--); total++; } else { break; } } } } @Override public void run() { sell(); } } class Main { public static void main(String[] args) throws InterruptedException { Ticket t = new Ticket(); Thread t1 = new Thread(t); Thread t2 = new Thread(t); t1.start(); t2.start(); for (int i = 0; i < 9999;++i) System.out.print(""); System.out.println(t.total); //测试卖出的票数 } }
时间: 2024-10-08 10:44:26