1.采用继承thread类方式:
public class T1 extends Thread{
public void run(){
}
}
public static void main(String[] args){
T1 t = new T1();
t.start();
}
优点:编写简单,如果需要访问当前线程,无需使用Thread.currentThread()方法,直接使用this,即可获得当前线程。
缺点:因为线程类已经继承了Thread类,所以不能再继承其他的父类。
2.采用使用runnable接口方式
public class T1 implements Runnable{
public void run(){
}
}
public static void main(String[] args){
T1 t = new T1();
Thread th = new Thread(t);
th.start();
}
优点:线程类只是实现了Runable接口,还可以继承其他的类。在这种方式下,可以多个线程共享同一个目标对象,所以非常适合多个相同线程来处理同一份资源的情况,从而可以将CPU代码和数据分开,形成清晰的模型,较好地体现了面向对象的思想。
缺点:编程稍微复杂,如果需要访问当前线程,必须使用Thread.currentThread()方法。
3.采用实现Callable接口方式
public class T1 implements Callable<返回值类型>{
public 返回值类型 call() throws Exception{
return 值;
}
}
public static void main(String[] args){
T1 t = new T1();
FutureTask<返回值类型> ft = new FutureTask<返回值类型>(t);
Thread th = new Thread(ft);
th.start();
}
Runnable和实现Callable接口的方式基本相同,不过是后者执行call()方法有返回值可以throws异常,前者线程执行体run()方法无返回值不能throws异常,因此可以把这两种方式归为一种这种方式与继承Thread类的方法之间的差别如下:
优点:线程只是实现Runnable或实现Callable接口,还可以继承其他类。这种方式下,多个线程可以共享一个target对象,非常适合多线程处理同一份资源的情形。
缺点:编程稍微复杂,如果需要访问当前线程,必须调用Thread.currentThread()方法。