线程创建的三种方式
1.继承Thread类
public class Test07 {
public static void main ( String[ ] args) {
new MyThread ( ) . start ( ) ;
}
}
class MyThread extends Thread {
@Override
public void run ( ) {
super . run ( ) ;
System. out. println ( "11111" ) ;
}
}
2.实现Runnable接口
public class Test08 {
public static void main ( String[ ] args) {
new Thread ( new MyThread2 ( ) ) . start ( ) ;
}
}
class MyThread2 implements Runnable {
@Override
public void run ( ) {
System. out. println ( "22222" ) ;
}
}
3.实现Callable接口
1.Thread()参数要放一个Runnable的一个实现类
public Thread ( Runnable target) {
init ( null, target, "Thread-" + nextThreadNum ( ) , 0 ) ;
}
2.RunnableFuture接口继承了Runnable接口
public interface RunnableFuture < V> extends Runnable , Future< V> {
void run ( ) ;
}
3.FutureTask实现了上边那个接口,而且它里边的构造方法可以传Callable
public class FutureTask < V> implements RunnableFuture < V> {
public FutureTask ( Callable< V> callable) {
if ( callable == null)
throw new NullPointerException ( ) ;
this . callable = callable;
this . state = NEW;
}
}
具体操作如下
public class Test09 {
public static void main ( String[ ] args) throws ExecutionException, InterruptedException {
MyThread3 myThread3 = new MyThread3 ( ) ;
FutureTask< String> task = new FutureTask < > ( myThread3) ;
new Thread ( task) . start ( ) ;
String s = task. get ( ) ;
System. out. println ( s) ;
}
}
class MyThread3 implements Callable < String> {
@Override
public String call ( ) throws Exception {
return "3333" ;
}
}
Callable 这里的泛型就是方法的返回类型,通过task.get()方法可以获得。而Runnable接口,没有返回类型