package tickect; class ticketnum implements Runnable { public int tickets = 100; String str = new String(); public void run() { while(true) { synchronized(str) { if (tickets>0) { System.out.printf("The Thread: %s is selling the %dth ticket!\n",Thread.currentThread().getName(),tickets); --tickets; try { Thread.sleep(20); } catch(Exception e) {} } else { break; } } } } } public class Tickect_test { public static void main(String [] args) { ticketnum ticketNum = new ticketnum(); Thread sellThread1 = new Thread (ticketNum); Thread sellThread2 = new Thread (ticketNum); sellThread1.start(); sellThread2.start(); } }
时间: 2024-10-08 16:26:57