线程创建方法
1、继承Thread,重写run方法
private static void one() {
class T extends Thread{
@Override
public void run() {
log.debug("one is running...");
}
}
T t = new T();
t.start();
}
简写
private static void one() {
Thread t = new Thread(){
@Override
public void run() {
log.debug("one is running...");
}
};
t.start();
}
结果如图
2、Runnable配合Thread
Thread代表线程
Runnable代表可运行的任务(要执行的代码)
Runnable实现run方法,创建的对象作为Thread的构造参数
private static void two() {
Runnable runnable = new Runnable() {
@Override
public void run() {
log.debug("two is running...");
}
};
Thread t = new Thread(runnable);
t.start();
// //简写
// Thread t = new Thread() {
// @Override
// public void run() {
// log.debug("two is running...");
// }
// };
// t.start();
// //lambda表达式
// Thread t = new Thread(() -> {
// log.debug("two is running...");
// });
// t.start();
}
3、FutureTask配合Thread
private static void three() {
//FutureTask间接继承了Runnable
FutureTask<Integer> task = new FutureTask<Integer>(() -> {
log.debug("three is running...");
return 1;
});
Thread t3 = new Thread(task);
t3.start();
}
FutureTask可以接受Callable类型的参数,同时间接继承了Runnable,所以FutureTask可以作为Thread的构造参数创建线程
结果如图
4、使用ThreadPoolExecutor执行任务
private static void four() {
ThreadPoolExecutor t1 = new ThreadPoolExecutor(
//核心线程数
2,
//最大线程数
3,
//救急线程存活时间
1,
//救急线程存活时间单位
TimeUnit.SECONDS,
//任务队列
new ArrayBlockingQueue<Runnable>(5),
//线程工厂,可以给线程起一个好名字
r -> new Thread(r, "t1"),
//拒绝策略
new ThreadPoolExecutor.AbortPolicy()
);
t1.execute(() -> {
log.debug("four is running...");
});
}
execute()接收Runnable类型的参数
结果如图
标签:Runnable,log,Thread,创建,void,线程,new,方法 From: https://www.cnblogs.com/WangJiQing/p/16988668.html