多线程二(Runnable接口)

来源:互联网 发布:特种设备考试软件 编辑:程序博客网 时间:2024/04/27 23:10
/*
 * 创建线程的第二种方式:实现Runable接口

 * 步骤:


 * 1.定义类实现Runnable接口。


 * 2.覆盖Runnable 中的run方法。

 * 将线程要执行的代码存放在run方法中。

 * 3.通过Thread类建立线程对象。


 * 4.将Runnable接口的子类对象作为实际参数传递给Thread类的构造函数。

 * 自定义的run方法属于Runnable接口的子类对象。所以要让线程去执行指定对象的run方法,就必须明确run方法的指定对象。


 * 5.调用Thread类的start方法,开启线程并调用Runnable接口中子类的run方法。


 * 6.实现方式和继承方式的区别:

 * a.实现方法(好处):可以避免但继承的局限性,在定义线程时,建议使用实现方法。
 * b.继承Thread:线程代码存放在Thread子类的run方法中。
 * c.实现Runnable:线程代码存放在接口子类的run方法中。
 */
class Ticket implements Runnable
{
private int tick=100;
public void run()
{
while(tick>0)
System.out.println(Thread.currentThread().getName()+"----sale:"+tick--);
}
}
public class RunnbleDemo {
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();
}
}
0 0