用Java模拟火车票发售情况
Java创建线程的方式有两种:
1.继承Thread重写run方法
2.实现Runnable接口的run方法
package base; /** *@author wenfan *@version 2019年4月1日下午7:29:22 */ public class Ticket { public static void main(String[] args) { TicketSellThread thread = new TicketSellThread(); new Thread(thread,"窗口1").start(); new Thread(thread,"窗口2").start(); new Thread(thread,"窗口3").start(); new Thread(thread,"窗口4").start(); } } class TicketSellThread implements Runnable{ private int ticketCount = 100; @Override public void run() { // TODO Auto-generated method stub while(ticketCount > 0) { Thread th = Thread.currentThread(); System.out.println(th.getName()+"正在发售"+ticketCount--+"票");; } } }
一般来说大部分的应用程序都会采用实现Runnable 接口来创建多线程