1.进程
1.1简介
进程是在操作系统中独立运行的一个程序,每个应用程序就对应着一个进程,多进程即为操作系统中同时运行多个应用。
打开任务管理器即可查看计算机的进程
1.2进程控制块抽象PCB
即Process Control Block,通过一个类将进程唯一标识pid、进程相关的程序信息、分配的资源、进程调度等信息包含在其中
// Java 伪码,无法直接运行
class PCB {
//内容信息
}
每一个 PCB 对象,就代表着一个实实在在运行着的程序,也就是进程,操作系统中通过各种数据结构将PCB对象组织起来,以便管理。
1.3CPU分配--进程调度
操作系统对CPU的资源分配采用时间模式:即不同的进程在不同的时间段去使用CPU
- 对于单核CPU而言,多个应用同时运行时,看似是多个进程同时运行,其实是在极短时间内CPU分别处理不同的进程,轮流执行不同的程序,因为时间较短所以表现出的是多个应用同时运行
- 而多核CPU则是实在的多个进程同时运行
1.4进程内存分配
操作系统对内存资源的分配采用的是空间模式,不同进程使用的内存空间不同,互不干扰、
2.线程
进程是系统调度的基本单位
线程是系统分配资源的基本单位
2.1简介
- 线程是进程里的一个执行流
- 线程包含在进程里面,每个进程至少有一个线程存在,即主线程
- 不同的进程所用的储存空间是不同的,而相同进程里的线程间共享一个内存空间
- 多个线程之间都是并发执行的
2.2线程使用
Java中提供了Thread类,是对操作系统的API的一种封装
- 继承Thread类,重写run方法,将要执行的语句写进run方法里
class MyThread extends Thread{ @Override public void run() { //下为执行语句 System.out.println("override run method."); } } public class TestDemo1 { public static void main(String[] args) { MyThread myThread = new MyThread(); //实例化对象 myThread.start(); //start启动线程 } }
- 实现Runnable接口,重写run方法
class MyRunnable implements Runnable{ @Override public void run() { System.out.println("Runnable implement."); } } public class TestDemo2 { public static void main(String[] args) { Thread thread = new Thread(new MyRunnable()); //实例化Thread,传入参数为新的Runnable对象 thread.start(); //执行线程 } }
- 使用匿名内部类,创建Thread子类对象
public class TestDemo3 { public static void main(String[] args) { Thread thread = new Thread(){ @Override public void run() { System.out.println("this is a thread."); } }; thread.start(); } }
- 使用匿名内部类,创建Runnable子类对象
public class TestDemo4 { public static void main(String[] args) { Thread thread = new Thread(new Runnable() { @Override public void run() { System.out.println("this is a thread."); } }); thread.start(); } }
- 使用Lambda表达式,创建Thread子类对象
public class TestDemo6 { public static void main(String[] args) { //方法1 Thread thread = new Thread(()->{ System.out.println("this is thread1."); }); thread.start(); //方法2 Thread thread1 = new Thread(()-> System.out.println("this is thread2.")); thread1.start(); } }
继承Thread类
- 线程执行的语句在run方法里
- 继承Thread后就无法再继承其他类
实现Runnable接口
- 线程执行的代码放在实现Runnable接口的类的run方法中
- 可以继承其他类,避免了单继承的局限性
- 适合多个相同程序代码的线程去处理同一个资源
- 增强程序的鲁棒性