/**
* 第一种方式实现买票
* */
class Ticket extends Thread
{
private static int num=100; //static num实现所有成员共享票,假如有100张票吧;
public void run() //100次循环卖完所有的票//因为票是共享的,所以4个对象共同卖完100张
{
for(int i=0;i<=100;i++)
{
if(num>0)
{
System.out.println(currentThread().getName()+"..................."+num--);//输出当前的线程的名称+卖的第几张票
}
}
}
}
public class Test2
{
public static void main(String[] args)
{
Ticket t1=new Ticket();//创建票对象
Ticket t2=new Ticket();
Ticket t3=new Ticket();
Ticket t4=new Ticket();
t1.start();
t2.start();
t3.start();
t4.start();
}
}
/**
* 第二种方式实现买票
* implements Ruannable 接口的方式
*
* */
class Ticket2 implements Runnable
{
private int num=100;
public void run()
{
for(int i=0;i<100;i++)
{
if(num>0)
{
System.out.println(Thread.currentThread().getName()+"......................................"+num--);
}
}
}
}
public class Test2
{
public static void main(String[] args)
{
Ticket2 t=new Ticket2();
Thread t1=new Thread(t);//把线程任务封装在Ruannable 接口中,任务不变,只是创建多个Thread对象并把任务传进去,让Ruannable他们去卖;
Thread t2=new Thread(t);
Thread t3=new Thread(t);
Thread t4=new Thread(t);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
|
|