/*
需求:简单的卖票系统
多窗口::::多线程
创建线程的第二种方式:实现Runnable接口。
步骤:
1,定义类实现 Runnable接口
2,覆盖 Runnable接口中的run方法。
将线程运行的代码存放于run方法中。
3,通过Thread类建立线程对象。
4,将Runnable接口的子类对象作为实际参数传递给Thread类的构造函数。、
为什么将Runnable接口的子类对象传递给Thread的构造函数。
因为,自定义的run方法所属的对象是runnable接口的子类对象。
所以要让线程去指定对象的run方法,就必须明确该run方法所属对象。
5,调用Thread类的start方法开启线程并调用Runnable接口子类的run放法。
实现方式和继承方式有什么区别呢?
实现方式好处:避免了单继承的局限性。
在定义线程时,建立使用实现方式。
两种方式的区别:
继承Thread:线程代码存放于Thread子类run方法中。
实现runnable:线程存在接口的子类的run方法。
*/
class Ticket implements Runnable// extends Thread
{
private int ticket = 10;
Object obj = new Object();
public void run()
{
while(true)
{
synchronized(obj)
{
if(ticket>0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"--- Sale:"+ticket--);
}
}
}
}
}
class TicketDemo
{
public static void main(String[] args)
{ Ticket t = new Ticket();
//Ticket t1 = new Ticket();
//Ticket t2 = new Ticket();
//Ticket t3 = new Ticket();
//Ticket t4 = 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();
}
}
多线程,卖票系统
最新推荐文章于 2022-07-20 11:18:55 发布