方法一,直接使用 Thread
import lombok.extern.slf4j.Slf4j;
@Slf4j(topic = "c.Test1")
public class Test1CreateThread {
public static void main(String[] args) {
Thread t = new Thread(){
@Override
// run 方法内实现了要执行的任务
public void run() {
log.debug("hello");
}
};
t.setName("t1");
t.start();
log.debug("hi");
}
}
方法二,使用 Runnable 配合 Thread
把【线程】和【任务】(要执行的代码)分开
● Thread 代表线程
● Runnable 可运行的任务(线程要执行的代码)
import lombok.extern.slf4j.Slf4j;
@Slf4j(topic = "c.Test1")
public class Test2CreateThread {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
public void run(){
// 要执行的任务
log.debug("aaaa");
}
};
// 创建线程对象
Thread t = new Thread( runnable,"threadName");
// 启动线程
t.start();
}
}
小结
● 方法1 是把线程和任务合并在了一起,方法2 是把线程和任务分开了
● 用 Runnable 更容易与线程池等高级 API 配合
● 用 Runnable 让任务类脱离了 Thread 继承体系,更灵活
方法三,FutureTask 配合 Thread
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
@Slf4j(topic = "c.Test1")
public class Test3CreateThread {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<Integer> task = new FutureTask<>(()->{
log.debug("hello");
return 100;
});
new Thread(task,"t3").start();
Integer result = task.get();
log.debug("结果是{}",result);
}
}