一,定义
进程是资源(CPU、内存等)分配的基本单位,具有一定功能的程序关于某个数据集合上的一次运行活动,进程是系统进行资源分配和调度的一个独立单位。
线程是进程的一个实体,是独立运行和独立调度的基本单位(CPU上真正运行的是线程)。线程自己基本上不拥有系统资源,只拥有一点在运行中必不可少的资源(如程序计数器,一组寄存器和栈),但是它可与同属一个进程的其他的线程共享进程所拥有的全部资源。
二, 为什么需要线程:
首先, "并发编程" 成为 "刚需".
1,单核 CPU 的发展遇到了瓶颈. 要想提高算力, 就需要多核 CPU. 而并发编程能更充分利用多核 CPU 资源.
2,有些任务场景需要 "等待 IO", 为了让等待 IO 的时间能够去做一些其他的工作, 也需要用到并发编程.
其次, 虽然多进程也能实现并发编程, 但是线程比进程更轻量.
1,创建线程比创建进程更快. 销毁线程比销毁进程更快. 调度线程比调度进程更快.
最后, 线程虽然比进程轻量, 但是人们还不满足, 于是又有了 "线程池" 和 "协程"
二,进程和线程的区别
1,进程是包含线程的. 每个进程至少有一个线程存在,即主线程。
2,进程和进程之间不共享内存空间. 同一个进程的线程之间共享同一个内存空间.
3,进程是系统分配资源的最小单位,线程是系统调度的最小单位。
三,创建线程
1,通过继承Thread类并实现run方法创建一个线程
class MyThread01 extends Thread{
@Override
public void run() {
System.out.println("hello, thread.");
}
}
public class test1 {
public static void main(String[] args) {
MyThread01 t = new MyThread01();
t.start();
}
}
2,通过实现Runnable接口,并实现run方法的方法创建一个线程
class MyRunnable01 implements Runnable{
@Override
public void run() {
System.out.println("hello, thread.");
}
}
public class test2 {
public static void main(String[] args) {
MyRunnable01 t1 = new MyRunnable01();
Thread t = new Thread(t1);
t.start();
}
}
3,通过Thread匿名内部类创建一个线程
public class test3 {
public static void main(String[] args) {
Thread t = new Thread(){
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
};
t.start();
}
}
4,通过Runnable匿名内部类创建一个线程
public class test4 {
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
t.start();
}
}
5,通过Lambda表达式的方式创建一个线程(推荐使用)
public class test5 {
public static void main(String[] args) {
Thread t = new Thread(() -> {
while (true) {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
t.start();
}
}