前面一节我们是通过继承Thread这个类来实现多线程,而如果当前类要继承其他类的时候,我们怎么来实现多线程呢?大家都知道,Java中只允许单从继承,也就是说不能在继承Thread这个类了,那设个时候怎么来实现多线程呢?其实,我们可以通过Runnable接口的方式实现多线程,查看API可以知道,Runnable接口中只定义了一个抽象方法:
public void run(){
}
使用Runnable接口实现多线程的格式如下。
class 类名称 implements Runnable{
属性...;
方法...;
public void run(){
线程主体;
}
}
同样,我们拿个例子来说明下:
class MyThread implements Runnable{
private String name;
public MyThread(String name){
this.name=name;
}
public void run(){
for(int i=0;i<5;i++){
System.out.println(name+"运行,i="+i);
}
}
};
public class ThreadTest{
public static void main(String args[]){
MyThread mt1=new MyThread("线程A");
MyThread mt2=new MyThread("线程B");
Thread t1=new Thread(mt1);
Thread t2=new Thread(mt2);
t1.start();
t2.start();
}
}
运行结果:
线程A运行,i=0
线程A运行,i=1
线程A运行,i=2
线程A运行,i=3
线程B运行,i=0
线程B运行,i=1
线程B运行,i=2
线程B运行,i=3
线程B运行,i=4
线程A运行,i=4