Java中创建线程的三种方式
1.继承Thread类创建线程
2.通过Runnable接口创建线程类
3.使用Callable+FutureTask(能够获取到线程执行结果)
继承Thread类
class MyThread extends Thread {
/**
* run 方法中的代码是线程具体要执行的业务代码
*/
@Override
public void run() {
System.out.println("我是run方法");
}
}
public class Test {
public static void main(String[] args) {
// 创建线程
MyThread thread = new MyThread();
// 注意这里启动线程应该是调用start方法而不是run方法
thread.start();
}
}
上面的写法有点繁琐,我们还可以使用以下匿名类的方式来实现
public class Test {
public static void main(String[] args) {
Thread thread = new Thread() {
@Override
public void run() {
System.out.println("我是run方法");
}
};
// 启动线程
thread.start();
}
}
缺点分析:继承了Thread类有个明显的缺点,Java语言是单继承的,如果继承了Thread类就不能继承其他类。
实现Runnable接口
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("我是run方法");
}
}
public class Test {
public static void main(String[] args) {
// 创建一个 Runnable 实现类
MyRunnable myRunnable = new MyRunnable();
// 创建线程
Thread thread = new Thread(myRunnable);
// 启动线程
thread.start();
}
}
为了方便使用更加简单的匿名和Lambda表达式来书写
public class Test {
public static void main(String[] args) {
// 使用匿名类创建一个 Runnable实例
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("我是run方法");
}
});
// 启动线程
thread.start();
}
}
public class Test {
public static void main(String[] args) {
// 使用 Lambda 匿名 Runnable 方式
new Thread(() -> System.out.println("我是run方法")).start();
}
}
使用Callable接口
// 定义普通实现 Callable 接口,返回一个 String 类型的结果(当然也可以返回其他类型的结果)
class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("我是call方法");
return "call";
}
}
public class Test {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 创建 Callable 普通类
MyCallable callable = new MyCallable();
// 使用 FutureTask 用于获取线程执行结果
FutureTask<String> futureTask = new FutureTask<>(callable);
// 创建线程
Thread thread = new Thread(futureTask);
// 启动线程
thread.start();
// 得到线程执行的结果
String result = futureTask.get();
}
}
public class Test {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 匿名类实现
FutureTask<String> futureTask = new FutureTask<>(new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println("我是call方法");
return "call";
}
});
// 创建线程
Thread thread = new Thread(futureTask);
// 启动线程
thread.start();
// 得到线程执行的结果
String result = futureTask.get();
}
}