多线程学习笔记(一) 创建线程的方式
什么是线程
(~~!这是写的第二遍了!第一遍,写完了,忘记保存了!!悲伤的一天开始了!),老生常谈,啥是线程!啥是进程,都是啥?(这个问题,后期专门出一片文章来解释,太麻烦了,本文主要讲解,线程的创建方式,关于线程与进程请参考:线程与进程之间的关系)
线程的创建方式
问题:线程创建的方式有哪几种,分别是什么?底层实现的原理是什么(面试官:我看着你吹牛逼!!静静的看着你)
实现Runabble接口
public class RunnableThreadTest{
public static void main(String[] args) {
Runnable run=()-> System.out.println(Thread.currentThread().getName());
new Thread(run).start();
}
}
继承Thread类
public class ExtendsThreadTest extends Thread{
@Override
public void run() {
// super.run();
}
}
线程池创建
public class ThreadFactoryTest {
public static void main(String[] args) {
ThreadPoolExecutor executor = new ThreadPoolExecutor(10,
10,
1,
TimeUnit.MINUTES,
new LinkedBlockingDeque<>());
Runnable run = ()->{
System.out.println(Thread.currentThread().getName());
};
for (int i = 0 ; i < 10 ; i++){
executor.execute(run);
}
executor.shutdown();
}
}
有返回值的Callable创建线程
public class CallableTask {
static Callable<Integer> callable = ()->{
return new Random().nextInt();
};
public static void main(String[] args) {
ExecutorService service = Executors.newSingleThreadExecutor();
Future<Integer> future = service.submit(callable);
Integer result = 0;
try {
result = future.get();
System.out.println(result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}finally {
service.shutdown();
}
}
}
定时器Timer
public class TimerThread {
public static void main(String[] args) throws InterruptedException{
System.out.println("start");
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println(new Date());
}
},3000,1000);
}
}
其他方式
public class OtherThread {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}).start();
}
}
lambad创建线程
public class LambadThread {
public static void main(String[] args) {
new Thread(()->System.out.println(Thread.currentThread().getName())).start();
}
}
首先,看一下源码,你会发现,它们最终都是基于Runnable或者继承Thread类实现的

首先,启动线程,调用start方法,而start方法最终还是会调用run方法,run方法写的很简单,首先来看,第一行首先判断一下,是不是等于null,第二行就是将target传递给run,其实一个target就是一个Runnable。继承Thread不也是重写run方法,看到最后,你就会发现,实现线程只有一种方法,但是,实现线程的方式会有很多种。
与其说是自己写的,不如说是我自己的学习笔记,哈哈!
本文参考:Java并发编程核心 78讲

浙公网安备 33010602011771号