一、什么是进程
1.程序
为了解决某一问题用计算机语言编写的命令的集合
2.进程
是程序的一次执行过程
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println(sp.format(date));//运行后即刻结束
}
}
try {
Thread.sleep(30000);//单位为ms,加上后程序需要运行30s才出结束
} catch (InterruptedException e) {
e.printStackTrace();
}
在任务管理器中查看
3.线程
线程(thread)又称为轻量级进程,线程是一个程序中(即一个进程中)实现单一功能的一个指令序列,是一个程序的单个执行流,存在于进程中,是一个进程的一部分(线程是进程中一个独立的功能序列,能自己完成一个单独的功能)
public class Test {
public static void main(String[] args) throws InterruptedException {//抛出异常
Date date = new Date();
System.out.println(date);
Thread.sleep(5000);//停顿5s
new TimeThread().start();//该方法执行完才执行下一个
Thread.sleep(30000);
}
}
class TimeThread extends Thread{
@Override
public void run() {//重写run()方法
Date date = new Date();
System.out.println(date);
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
重写run()方法操作
运行后在任务管理器中可以看到
二、线程与进程的关系
①一个进程可以包含多个线程,而一个线程必须在一个进程之内运行;同一进程中的多个线程之间采用抢占式独立运行;(抢占CPU的使用权)
单位时间内计算机只有一个程序在运行,但是由于切换速度很快看起来很多个程序一起运行
public class Test {
public static void main(String[] args) throws InterruptedException {//抛出异常
new CounterThread().start();
new TimeThread().start();//两个线程抢占式运行输出
}
}
class CounterThread extends Thread{
int i = 0;
@Override
public void run() {
while (true) {
System.out.println(i++);//死循环,计数器线程
}//更强势所以抢占的次数更多
}
}
class TimeThread extends Thread{
@Override
public void run() {
while (true) {//死循环,时间线程
Date date = new Date();
System.out.println(date);
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
运行结果
②线程有独立的执行堆栈、程序计数器(用于记录当前的线程执行到了哪一步,抢占到CPU资源是才能继续执行下去)和局部变量;但是没有独立的存储空间,而是和所属进程中的其它线程共享存储空间;
③操作系统将进程作为分配资源的基本单位,而把线程作为独立运行和独立调度的基本单位,由于线程比进程更小,基本上不拥有系统资源,故对它的调度所付出的开销就会小得多,能更高效的提高系统多个程序间并发执行的速度
三、如何创建线程
①创建一个线程继承Thread类,重写run()方法
public class Test {
public static void main(String[] args) throws InterruptedException {
new CounterThread().start();
}
}
class CounterThread extends Thread{
int i = 0;
@Override
public void run() {
while (true) {
System.out.println(i++);
}
}
}
②实现一个Runnable接口,实现run抽象方法
public class Test {
public static void main(String[] args) throws InterruptedException {
new Thread(new CounterThread()).start();//new CounterThread()为上转型对象
}
}
class CounterThread implements Runnable{
int i = 0;
public void run() {
while (true) {
System.out.println(i++);
}
}
}
由于Runnable是函数式接口,可以用Lambda表达式
new CounterThread().start();
//改成
new Thread(()-> { System.out.println(1); }).start();