1.定义 |
-
进程:进程(Process)是计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,是操作系统结构的基础。在早期面向进程设计的计算机结构中,进程是程序的基本执行实体;在当代面向线程设计的计算机结构中,进程是线程的容器。程序是指令、数据及其组织形式的描述,进程是程序的实体。
解释:程序的一次执行过程,是系统运行的基本单位,是动态的
-
线程:有时被称为轻量级进程(Lightweight Process,LWP),是程序执行流的最小单元。一个标准的线程由线程ID,当前指令指针(PC),寄存器集合和堆栈组成。另外,线程是进程中的一个实体,是被系统独立调度和分派的基本单位,线程自己不拥有系统资源,只拥有一点儿在运行中必不可少的资源,但它可与同属一个进程的其它线程共享进程所拥有的全部资源。
-
解释:与进程相似,是进程的一个执行单位,一个进程可以产生多个线程。
-
并发:指在同一时刻只能有一条指令执行,但多个进程指令被快速的轮换执行,使得在宏观上具有多个进程同时执行的效果,但在微观上并不是同时执行的,只是把时间分成若干段,使多个进程快速交替的执行。
-
解释:多个线程访问同一资源
-
并行;指在同一时刻,有多条指令在多个处理器上同时执行。所以无论从微观还是从宏观来看,二者都是一起执行的
-
解释:一边干嘛一遍干嘛(我一边看电视一边吃西瓜)
-
2.为什么用? |
- 提高CPU利用率
解释:单核时代,我们只能等cpu干完一件事在干一件事,现在都是多核时代,我们当然要一边看电视一边吃零食啦
3.怎么用? |
- 创建线程的方式
- 继承java.lang.Thread 类
- 实现runnable接口
- 实现callable接口
- 代码
//继承Thread类
public class Test1 {
public static void main(String[] args) {
//创建线程
MyThread1 thread1=new MyThread1("线程1");
MyThread1 thread2=new MyThread1("线程2");
MyThread1 thread3=new MyThread1("线程3");
//开启线程
thread1.start();
thread2.start();
thread3.start();
System.out.println("主线程");
}
}
class MyThread1 extends Thread{
String s;
public MyThread1(String s) {
this.s=s;
}
@Override
public void run() {
System.out.println(s);
}
}
//实现runnable接口
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
long startTime1 = System.currentTimeMillis();
try {
ExamPaperModel examPaperModel = onlineExamServiceImpl.queryPaperAndRecord(examineeId, templateId);
} catch (Exception e) {
log.error("失败,该examineeId为{}", examineeId, e);
} finally {
System.out.println(Thread.currentThread() + " spent time:" + (System.currentTimeMillis() - startTime1));
}
}
}
//实现callable接口
public class CallTest implements Callable<String>{
String s;
public CallTest(String s) {
this.s=s;
}
//重写callable接口的call方法
@Override
public String call() throws Exception {
System.out.println(s);
return s;
}
}