众所周知,在JAVA中实现多线程有两种方式:
一种是[color=red]继承于Thread类[/color]
一种是[color=red]实现Runnable接口[/color]
本质相同的实现机制,之所以有两种实现方式,一方面针对不同爱好的用户群体,另外可能是因为JAVA不支持多继承,一旦你的类已经继承一个父类就无法再继承Thread类了,这个时候只有实现Runnable接口。
示例代码如下:
继承
public class MyThread extends Thread{
private String thrName;
public MyThread(String name){
this.thrName = name;
}
public void run(){
try {
Thread.currentThread().sleep(50);
System.out.println(this.thrName+" start");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
实现接口
public class MyThreadRunnable implements Runnable {
private String thrName;
public MyThreadRunnable(String name){
this.thrName = name;
}
public void run() {
// TODO Auto-generated method stub
try {
Thread.currentThread().sleep(25);
System.out.println(this.thrName+" start");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
一种是[color=red]继承于Thread类[/color]
一种是[color=red]实现Runnable接口[/color]
本质相同的实现机制,之所以有两种实现方式,一方面针对不同爱好的用户群体,另外可能是因为JAVA不支持多继承,一旦你的类已经继承一个父类就无法再继承Thread类了,这个时候只有实现Runnable接口。
示例代码如下:
继承
public class MyThread extends Thread{
private String thrName;
public MyThread(String name){
this.thrName = name;
}
public void run(){
try {
Thread.currentThread().sleep(50);
System.out.println(this.thrName+" start");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
实现接口
public class MyThreadRunnable implements Runnable {
private String thrName;
public MyThreadRunnable(String name){
this.thrName = name;
}
public void run() {
// TODO Auto-generated method stub
try {
Thread.currentThread().sleep(25);
System.out.println(this.thrName+" start");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}