java多线程之Runnable

来源:互联网 发布:跑车手机主题软件 编辑:程序博客网 时间:2024/05/29 08:39


public class Test implements Runnable {public static void main(String []args){Test tt = new Test();Thread t = new Thread(tt);//等价于Thread t = new Thread (new Test);t.start();//通过Thread类的start方法启动和main方法并列的线程
tt.m1();//main方法中调用m1方法的线程
} 
public void run(){
System.out.println("I am Run");
}public void m1() {System.out.println("I am t1");}}


通过实现Runnable接口实现多线程比通过继承Thread类更好些 因为java只能单继承 而通过实现Runnable接口可以让主类有更多的扩展空间

通过实现Runnable 接口创建多线程的话需要通过Thread类的start方法启动线程  所以需要new一个Thread类的对象  该线程运行的是run方法(无论是继承Thread类 还是实现Runnable接口来创建线程 ,创建的线程都是运行Run方法);

run()方法是多线程程序的一个约定。所有的多线程代码都在run方法里面。Thread类实际上也是实现了Runnable接口的类。

在启动的多线程的时候,需要先通过Thread类的构造方法Thread(Runnable target) 构造出对象,然后调用Thread对象的start()方法来运行多线程代码。

实际上所有的多线程代码都是通过运行Thread的start()方法来运行的。因此,不管是扩展Thread类还是实现Runnable接口来实现多线程,最终还是通过Thread的对象的API来控制线程的,熟悉Thread类的API是进行多线程编程的基础

1 0