一、继承Thread类,重写run方法
public class MyThread extends Thread { @Override public void run ( ) { System . out. println ( "I am a child thread" ) ; }
}
public class ThreadTest { public static void main ( String [ ] args) { new MyThread ( ) . start ( ) ; }
}
优点:
获取当前线程使用this,无须使用Thread.currentThread()方法 方便传参
缺点:
Java不支持多继承 任务和代码没有分离,不能执行多份任务代码
二、 实现Runnable接口的run方法
public class ThreadTest { public static void main ( String [ ] args) { Runnable task = new Runnable ( ) { @Override public void run ( ) { System . out. println ( "runnable" ) ; } } ; new Thread ( task) . start ( ) ; }
}
缺点
三、使用FutureTask
public class ThreadTest { public static void main ( String [ ] args) { FutureTask < String > futureTask = new FutureTask < > ( new Callable < String > ( ) { @Override public String call ( ) { return "hello" ; } } ) ; new Thread ( futureTask) . start ( ) ; try { String result = futureTask. get ( ) ; System . out. println ( result) ; } catch ( Exception e) { e. printStackTrace ( ) ; } }
}