线程的常见的几种创建方式
线程的几种创建方式
1. 继承Thread
public class T01 {
private static class MyThread extends Thread {
@Override
public void run() {
System.out.println("第一种创建方式:继承Thread类");
}
}
public static void main(String[] args) {
// 创建线程
MyThread t = new MyThread();
// 启动线程
t.start();
}
}
2. 实现Runnable接口
public class T02 {
private static class MyRun implements Runnable {
@Override
public void run() {
System.out.println("第二种创建方式:实现Runnable接口,重写run方法");
}
}
public static void main(String[] args) {
// 创建线程
Thread t = new Thread(new MyRun());
// 启动线程
t.start();
}
}
3. 实现Callable接口
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class T04 {
private static class MyCall implements Callable {
@Override
public Object call() throws Exception {
int a = 1;
int b = 2;
System.out.println("第四种创建方式:实现Callable接口");
return a + b;
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 创建任务
FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyCall());
// 创建线程
Thread t = new Thread(futureTask);
// 启动线程
t.start();
// 获取线程执行的返回值
System.out.println("线程执行的返回值:" + futureTask.get());
}
}
4. lamda表达式函数
public class T03 {
public static void main(String[] args) {
// 创建线程
Thread t = new Thread(() -> {
System.out.println("第三中创建方式:lamda表达式函数");
});
// 启动线程
t.start();
}
}
5. 线程池
import java.util.concurrent.*;
public class Th05 {
private static class MyCall implements Callable {
@Override
public Object call() throws Exception {
System.out.println("第五种创建方式:线程池");
return "success";
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 创建任务
FutureTask<String> task = new FutureTask<String>(new MyCall());
// 线程池
ExecutorService service = Executors.newCachedThreadPool();
Future<?> future = service.submit(task);
System.out.println(task.get());
service.shutdown();
}
}
上一篇:
通过多线程提高代码的执行效率例子
下一篇:
C语言 用指针实现矩阵转置
