/*
* 这是卖票类,继承Thread类
*
*/
class TicketDemo extends Thread
{
private static TicketDemo t = new TicketDemo();
private int tick = 100;
private TicketDemo()
{
super();
}
public static TicketDemo getTicketDemo()
{
return t;
}
public void run()
{
while(true)
{
if(tick>0)
System.out.println(Thread.currentThread().getName()+"..."+tick--);
}
}
}
public class TicketExe {
/**
* 需求:两个买票同时售票,可以定义一个单例设计模式
* 这种创建方式特别不靠谱,因为相当于一个类对象跑了2次
*
*
* 也可以建立两个买票对象,公用数据设计成静态
*
*/
public static void main(String[] args)
{
TicketDemo t1 = TicketDemo.getTicketDemo();
TicketDemo t2 = TicketDemo.getTicketDemo();
t1.start();
t2.start();
// TicketRunnable t = new TicketRunnable();//如何区分这两个同步线程
//
// Thread t1 = new Thread(t);
// Thread t2 = new Thread(t);
// t1.start();
// t.setFlag(false);
// t2.start();
}
}
代码运行结果,如下:
Exception in thread "main" Thread-0...100java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at Java_13.TicketExe.main(TicketExe.java:20)Thread-0...99
Thread-0...98
Thread-0...97
Thread-0...96
Thread-0...95
Thread-0...94
Thread-0...93
Thread-0...92
Thread-0...91
Thread-0...90
Thread-0...89
Thread-0...88
Thread-0...87
到结束
|