Java多线程实例之卖票

public class MyThread implements Runnable{ //电影票100张 private int tickets = 100; @Override public void run() { while(true){ synchronized (this){ if(tickets>0){ //获得当前线程的名称 try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"正在出售第"+tickets--+"张票"); } } } }}public class SaleTickets { public static void main(String[] args) { //创建资源对象 MyThread m = new MyThread(); //创建三个处理线程 Thread t1 = new Thread(m,"窗口1"); Thread t2 = new Thread(m,"窗口2"); Thread t3 = new Thread(m,"窗口3"); //开启线程 t1.start(); t2.start(); t3.start(); }}

你可能感兴趣的:(JavaSE,多线程,卖票,java,java基础)