线程创建方法
JAVA多线程实现方式主要有三种:继承Thread类、实现Runnable接口、实现Callable接口。其中前两种方式线程执行完后都没有返回值,只有最后一种是带返回值的。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import com.sun.org.apache.xpath.internal.functions.FuncTrue;
//线程的创建方式
public class ThreadTest {
public static void main(String[] args) {
//第一种方式调用
new Mythread1().start();
//第二种方式调用
new Thread(new Mythread2()).start();
//第三种方式调用
FutureTask<Integer> futureTask = new FutureTask<Integer>(new Mythread3());
new Thread(futureTask).start();
//接收并打印返回值
try {
Integer integer = futureTask.get();
System.out.println("返回值的是" + integer);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
//1.继承Thread类
class Mythread1 extends Thread{
@Override
public void run() {
System.out.println("这是继承Thread类。");
}
}
//2.实现Runnable接口
class Mythread2 implements Runnable{
@Override
public void run() {
System.out.println("这是实现Runnable接口。");
}
}
//3.实现Callable接口(与上面两个不同,需要返回值)
class Mythread3 implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("这是实现Callable接口");
return 10;
}
}