💗一. 创建和运行线程 💗
方法一,直接使用 Thread
public class test01 {
public static void main(String[] args) {
// 构造方法的参数是给线程指定名字
Thread thread = new Thread("t1") {
// 重写的run方法内实现了要执行的代码
@Override
public void run() {
// 要执行的任务
log.debug("hello,world!");
}
};
// 启动线程
thread.start();
}
}
控制台输出 :17:38:50.515 [t1] DEBUG thread01.test01 - hello,world!
方法二,使用 Runnable 配合 Thread
public class test01 {
public static void main(String[] args) {
// 创建任务对象
Runnable runnable = new Runnable() {
@Override
public void run() {
log.debug("hello,world!");
}
};
// 参数1 是任务对象; 参数2 是线程名字
Thread t2 = new Thread(runnable, "t2");
t2.start();
}
}
控制台输出 :17:43:23.974 [t2] DEBUG thread01.test01 - hello,world!
JDK8 以后可以使用 lambda表达式
// 创建任务对象
Runnable runnable = () -> log.debug("hello,world!");
// 参数1 是任务对象; 参数2 是线程名字
Thread t2 = new Thread(runnable, "t2");
t2.start();
原理之 Thread 与 Runnable 的关系
方式二是重写了Runnable 接口中的run方法,
然后又将Runnable 对象传到Thread 类中调用run方法,
方式一是直接重写了Thread 类中的run方法
方法三,FutureTask 配合 Thread
public class test03 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 创建任务对象,<>里是泛型,这里就定义为String
Callable<String> callable = new Callable<String>() {
@Override
public String call() throws Exception {
return "测试";
}
};
//同样<>里是泛型,这里就定义为String
FutureTask<String> futureTask = new FutureTask<>(callable);
// 参数1 是任务对象; 参数2 是线程名字
new Thread(futureTask, "t3").start();
// 获取结果
String result = futureTask.get();
log.debug("结果是:{}", result);
}
}
控制台输出 : 19:43:45.383 [main] DEBUG thread01.test03 - 结果是:测试
可以看到,在Callable接口中的call方法是有一个泛型的返回值的,而且可以抛出异常,而Runnable中的run方法是不能抛异常的;
FutureTask类是实现了一个叫RunnableFuture的接口
而RunnableFuture里面其实是继承了Runnable接口的;
此外还继承了一个Future接口;它里面就有获取返回的执行结果的get方法,而run方法是没有返回结果的,是void
以上就是我总结的一些创建线程的一些方式,在这里先不涉及线程池,线程池以后会单独介绍一下~