多线程(卖票实例)

分析:假设有100张票,四个窗口同时在卖。 实现多线程有两种方法,一个是继承Thread类,一个是实现Runnable接口。 这个例子是用第二种方法做的。 /* * * 需求:买票 * * */ class Ticket implements Runnable { private int num=100;//假设有100张票 Object obj=new Object(); public void run() { while(true) { synchronized(obj) { if(num>0) { try { Thread.sleep(10); } catch (InterruptedException e) { } System.out.println(Thread.currentThread().getName()+".sale.."+num--); } } } } } public class ThreadDemo { public static void main(String[] args) { Ticket t=new Ticket(); Thread t1=new Thread(t);//四个窗口同时卖票 Thread t2=new Thread(t); Thread t3=new Thread(t); Thread t4=new Thread(t); t1.start(); t2.start(); t3.start(); t4.start(); } }
原文地址:https://www.cnblogs.com/stonewu/p/3649937.html