创建线程的三种方法
2018-05-19 本文已影响0人
胜杰pro
Java 提供了三种创建线程的方法:
- 通过实现 Runnable 接口;
- 通过继承 Thread 类本身;
- 通过 Callable 和 Future 创建线程。
通过实现 Runnable 接口来创建线程
public class RunnableTest {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("runnable");
}
});
thread.start();
}
}
通过继承Thread来创建线程
public class ThreadTest {
public static void main(String[] args) {
new ThraedDemo().start();
}
private static class ThraedDemo extends Thread {
@Override
public void run() {
super.run();
System.out.println("extends thread");
}
}
}
通过 Callable 和 Future 创建线程
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CallableThreadTest {
public static void main(String[] args) {
FutureTask<Integer> ftt = new FutureTask<>(new CallableThreadDemo());
new Thread(ftt).start();
try {
//获得子线程执行结束后的返回值
System.out.println(ftt.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
private static class CallableThreadDemo implements Callable<Integer> {
@Override
public Integer call() throws Exception {
return 1;
}
}
}