需求:多个窗口售票
创建线程的第二种方式:实现Runnable接口
1.定义实现Runnable接口
2.覆盖Runnable中的run()方法
3.通过Thread类建立线程对象
4.将Runnable子类对象作为参数传递给Thread的构造函数,因为Runnable子类对象有自定义的run方法,要让线程运行指定的run方法
5.调用Thread的start方法
用实现方法好!避免的单继承的局限性
class Ticket implements Runnable
{
private int tick = 100;
public void run()
{
while(true)
{
if(tick>0)
{
System.out.println(Thread.currentThread().getName()+"sale: "+tick--);
}
}
}
}
class Test3
{
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();
}
}