本文主要是介绍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(); }}这篇关于Java多线程实例之卖票的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!