目录
1. 线程概念
2. 创建线程的多种方式
2.1 继承自Thread类,重写run方法.
2.2 实现Runnable接口,重写run方法.
2.3 继承Thread类,使用匿名的内部类
2.4 实现Runnable,使用匿名内部类
2.5 lambda表达式
3. 它与进程的区别和联系
1. 线程概念
线程是更轻量级的进程,是操作系统调度的基本单位,一个进程中的多个线程共用同一个进程资源(资源复用).多个线程可以在一个CPU核心上通过不断快速调度执行,也可以在多个CPU核心上同时执行. 举个例子:学校的一号食堂算一个进程,那么线程就是食堂的窗口,一个食堂有多个窗口.每个食堂窗口都占用一号食堂的某个位置.
注:只有第一个线程创建时,才会分配独立的资源,再次创建新的线程后,会大量减少申请的资源,提高创建和销毁的效率.此外,如果一个进程中的某个线程出现异常,那么可能会影响整个进程崩溃.
2. 创建线程的多种方式
默认会有一个main主线程.start()方法会创建新的线程,而单独调用run()方法不会创建新的线程.
//1.继承Thread类,重写run方法
class ThreadDemo1 extends Thread{@Overridepublic void run() {while (true) {System.out.println("ThreadDemo1");try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}
}//在main方法中Thread thread1 = new ThreadDemo1();//1.继承Thread类,重写run方法//ThreadDemo1thread1.start();
//2.实现Runnable接口,重写run方法
class ThreadDemo2 implements Runnable {@Overridepublic void run() {while (true) {System.out.println("ThreadDemo2");try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}
}//在main方法中//2.实现Runnable接口,重写run方法//ThreadDemo2Runnable runnable = new ThreadDemo2();Thread thread2 = new Thread(runnable);thread2.start();
//3.使用匿名内部类,继承Thread类Thread thread3 = new Thread(new Thread() {@Overridepublic void run() {while (true) {System.out.println("ThreadDemo3");try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}});thread3.start();
//4.使用匿名内部类,实现Runnable接口Thread thread4 = new Thread(new Runnable() {@Overridepublic void run() {while (true) {System.out.println("ThreadDemo4");try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}});thread4.start();
//5.使用lambda表达式Thread thread5 = new Thread(() -> {while (true) {System.out.println("lambda");try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}});thread5.start();
● 区别
① 线程是操作系统调度运行的基本单位,而进程是操作系统资源分配的基本单位.
② 每个进程有独立的资源,而同一进程的多个线程共用同一份进程的系统资源.
③ 一个程序并发完成多个任务,采用多线程实现,更高效且节约资源,但不具有隔离性.而多进程是为了保证多个程序间的隔离性,相互不影响.
● 联系
一个进程包含一个或多个线程,同一个进程中的一个线程出现异常,那么该进程很容易会崩溃,且该进程中的其它线程也无法正常调度.
分享完毕~
下一篇:mongodb学习笔记