本文主要讲线程的创建和启动,生命周期
线程的释义(What)
百度百科如下:
为什么要有线程(Why)
在Java中很多文件IO操作和网络IO操作都是比较耗时的,比如下载10个文件到本地,这时一般的程序会一个一个
文件的下载,加入使用多线程操作会将10个文件同时下载,这个时候会节省好多时间.
本文的例子是读取数据库内容并写入本地文件,话不多说,让我们一起看代码吧!
线程的创建方式(How)
- 未使用多线程之前
/**
* @author alone
* @date 2020/5/12
*/
public static void main(String[] args) {
readFromDataBase();
writeDataToFile();
}
private static void readFromDataBase() {
//read data from database and handle it.
try {
println("Begin read data from db.");
Thread.sleep(30_000);
println("Read data done and start handle it.");
} catch (InterruptedException e) {
e.printStackTrace();
}
println("The data handle finish and successfully.");
}
private static void writeDataToFile() {
try {
println("Begin write data to file.");
Thread.sleep(20_000);
println("Write data done and start handle it.");
} catch (InterruptedException e) {
e.printStackTrace();
}
println("The data handle finish and successfully.");
}
private static void println(String message) {
System.out.println(message);
}
- 使用Thread类创建线程
public static void main(String[] args) {
// readFromDataBase();
// writeDataToFile();
Thread thread1 = new Thread(){
@Override
public void run() {
readFromDataBase();
}
};
Thread thread2 = new Thread(){
@Override
public void run() {
writeDataToFile();
}
};
thread1.start();
thread2.start();
}
- 使用Runnable接口创建线程
public static void main(String[] args) {
// readFromDataBase();
// writeDataToFile();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
readFromDataBase();
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
writeDataToFile();
}
});
thread1.start();
thread2.start();
}
通过上图源码看出Runable接口是一个函数式接口,所以使用Java8 Lamda表达式改造如下
public static void main(String[] args) {
// readFromDataBase();
// writeDataToFile();
new Thread(()->readFromDataBase()).start();
new Thread(()->writeDataToFile()).start();
}
线程的启动
我们看到线程的启动方法使用的是Thread类的start()方法,并不是直接调用run()方法,这里的原因如下:
如果直接调用run方法的话 只是方法之间的调用,并不会创建线程,我们可以通过阅读源码的方式看到.
调用start()方法底层其实是调用了JNI C++的底层方法
线程的生命周期
本图片来自线程的生命周期,了解详细生命周期的变化请移步前文连接.
线程的生命周期是由下列状态组成:
- new(新建状态)
- Runable(就绪状态)
- Running(运行状态)
- Block(阻塞状态)
- Dead活Terminate(死亡状态)