一.进程和线程的关系和区别
1. 概念
- 进程:是并发执行的程序在执行过程中分配和管理资源的基本单位,是一个动态概念,竟争计算机系统资源的基本单位
- 线程:是进程的一部分,是 CPU 调度的一个基本单位。
2.关系和区别
- 进程是一段正在执行的程序,是资源分配的基本单元,而线程是CPU调度的基本单元。
- 进程间相互独立,进程之间不能共享资源。一个进程至少有一个线程,同一进程的各线程共享进程的资源(堆区、方法区)。
- 线程的创建和切换开销比进程小,引入线程的概念可以带来更好的并发的。
- 进程间通信可能基于:socket、共享内存、消息队列等,但一个进程内的线程通信通过共享变量就能做到。
二.sleep和yield
三.interupt
- 如果线程A处于运行态,将其打断,不会影响其运行,打断标记为true。如果线程A处于阻塞态,将其打断,线程A抛出InterruptedException,打断标记被清空(在抛异常之前,打断标记已被清空),为false。
- 根据interrupt的特点,写出两阶段终止模式,代码如下:
class Time
{
public static void sleep(int millSecond)
{
try {
Thread.sleep(millSecond);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
class TwoPhaseTermination
{
private Thread monitor;
//start thread
public void start()
{
monitor=new Thread()
{
@Override
public void run() {
while (true)
{
if (monitor.isInterrupted())
{
System.out.println("Finish something , then stop!!!!");
break;
}
/*
执行case1时被打断,发生InterruptedException,monitor的打断tag重置为false,进入catch块,然后再次被打断,monitor的打断tag为true,下次循环就跳出了
执行case2时被打断,不发生异常,不进入catch块,monitor的打断tag为true,下次循环就跳出了
*/
try {
Thread.sleep(1000); //case1
System.out.println("Monitor.......");//case2
}
catch (InterruptedException e)
{
System.out.println("Be interupted while sleeping!!!");
monitor.interrupt();
System.out.println("Change interupted tag to true!!");
}
}
}
};
monitor.start();
}
public void stop()
{
monitor.interrupt();
}
}
public class test {
public static void main(String[] args)throws Exception {
TwoPhaseTermination t=new TwoPhaseTermination();
t.start();
Time.sleep(3500);
t.stop();
}
}
三.park unpark
参考:
https://blog.csdn.net/e891377/article/details/104551335
https://blog.csdn.net/hengyunabc/article/details/28126139
四.Daemon线程
就记住一句话:当一个Java虚拟机中不存在非Daemon线程的时候,Java虚拟机将会退出。