---------------------- ASP.Net+Android+IOS开发、.Net培训、期待与您交流! ----------------------
package com.test;
public class Tacket implements Runnable
{
private int tickets=100;
public void run()
{
while(tickets>0)
{
System.out.println(Thread.currentThread().getName()+"......"+(tickets--));
}
}
public static void main(String args[])
{
Tacket t = new Tacket();
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();
}
}
作用:实现多线程的方式之一,相比thread实现方式的好处是:避免了继承的局限,一个类可以继承多个接口;适合资源共享;
步骤解释:
1、定义类实现Runnable接口
2、实现Runable接口中的run 方法
3、通过Thread类建立线程对象,建立对象时 传入的构造函数的参数是Runnable接口的实现类
4、Thread 类的start方法 开启线程,并调用Runnable接口实现类的run 方法
后记:
由此引发的抽象类和接口的区别:
抽象类 只能实现单一继承,例如: class ticket extends Thread 这样之后 ticket 就不能再继承其他类了,因为java 只支持单继承,
接口, 避免了单继承的局限性,在定义线程时 建议使用Runnable接口,调用时 使用 如上代码中的方式;