“进程”与“线程”
在进行线程实现方式的总结之前,我们先来了解一下“进程”的基本概念、“进程”与“线程”的联系和区别。
进程 :一个应用程序是一个或者多个进程;是系统进行资源分配和调度的基本单位,是操作系统结构的基础。
一个进程中至少有一个线程,线程是进程中的实体,是操作系统调度的最小单位。线程本身是不会独立存在的,进程中的多个线程可以共享进程的资源,也可以独立调度。
使用多线程:可以充分利用多核CPU的优势
线程状态
1 --- NEW(新建状态-当一个线程被创建后,启动之前,就处于该状态)
public class test01 {
public static void main(String[] args) {
Thread th = new Thread();
System.out.println(th.getState());
}
}
输出:NEW
2 --- TERMINATED(消亡状态-当线程把任务执行结束后,就处于该状态)
public class test02 {
public static void main(String[] args) throws InterruptedException {
Thread th = new Thread();
th.start();
th.run();
Thread.sleep(1000);
//在这个时间段内,线程肯定把run方法中的内容执行完了,线程就结束了
System.out.println(th.getState());
}
}
输出: TERMINATED
3 --- RUNNABLE(可运行状态-当一个线程正在执行任务,就处于该状态)
public class test03 {
public static void main(String[] args) throws InterruptedException {
Runnable r = new Runnable() {
@Override
public void run() {
while(true) {
}
}
};
Thread th = new Thread(r);
th.start();
Thread.sleep(100);
System.ou