多线程的小DEMO (模拟卖票系统)
import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; import javax.swing.text.DefaultEditorKit.InsertBreakAction; public class Ticket implements Runnable { private int poll ; private int num = 900; private List<String> list = new ArrayList<>(); private static NumberFormat nf = NumberFormat.getInstance(); static{ nf.setMinimumIntegerDigits(4); nf.setGroupingUsed(false); } public Ticket(){} public Ticket(int poll){ this.poll = poll; } public void run() { while(true){ synchronized (this) { if (num >= poll) { System.out.println("票已售完"); return; } String tName = Thread.currentThread().getName(); num++; System.out.println(tName + "\t出售\t" +nf.format(num)); } try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args) { Runnable target = new Ticket(1000); String windows = "ABCDE"; for(int i = 0; i<windows.length();i++){ Thread te = new Thread(target, "柜台"+windows.charAt(i)); te.start(); } } }