Java 线程的相关知识概念
进程:代码在数据集合上的一次运行活动,是系统(操作系统)进行资源分配和调度的基本单位
线程:线程是进程的一个执行单位,一个进程中至少有一个线程,进程中的多个线程共享进程中的资源,是cpu执行的基本单位,也是cpu分配(cpu资源)的基本单位
程序计数器:一块内存区域,记录当前线程要执行的指令地址,并且是私有的。(因为Cpu是时间片的执行各个线程的代码,所以必须有一个程序计数器记录当前代码的执行情况,如果执行是native 方法,pc计数器记录的是undefined地址,只有执行Java代码时才记录java的下一个指令地址)
栈:每个线程是私有的一份,用于存储改线程的局部变量(只能改线程访问),还存放线程的调用栈帧
**方法区:**存放Jvm加载的类,常量及静态变量等信息,线程共享的
死锁的产生条件:
互斥:获取到资源互斥
请求和保持:线程至少获得一个资源,但是又提出新的资源,这个资源又被其他线程占有
不可剥夺:获得资源在线程使用完之前不能被剥夺
循环等待:发生死锁时,必然存在资源的循环等待
写一个顺序获取锁导致死锁的案例
// 一个按顺序获取资源的死锁
public class DeadLockDemo {
public static Object objectA = new Object();
public static Object objectB = new Object();
public static void main(String[] args) {
Thread threadA =new Thread(){
@Override
public void run() {
synchronized (objectA){
System.out.println("thread a get objectA");
synchronized (objectB) {
try {
System.out.println("thread a get objectB");
System.out.println("thread a release objectA");
objectA.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
Thread threadB =new Thread(){
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (objectA){
System.out.println("thread b get objectA");
synchronized (objectB) {
try {
System.out.println("thread b get objectB");
System.out.println("thread b release objectA");
objectA.wait();//这里只会释放objectA
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
threadA.start();
threadB.start();
}
}
结果:
thread a get objectA
thread a get objectB
thread a release objectA
thread b get objectA
notity 和notifyAll 的区别
notity :唤醒之前调用wait 的其中一个线程
notifyAll :唤醒之前调用wait 的所有线程
// notify 和 notifyAll的区别
public class NotifyDemo {
public static Object objectA = new Object();
public static void main(String[] args) {
Thread threadA =new Thread(){
@Override
public void run() {
synchronized (objectA){
try {
System.out.println("threadA begin wait");
objectA.wait();
System.out.println("threadB end wait");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread threadB =new Thread(){
@Override
public void run() {
synchronized (objectA){
try {
System.out.println("threadB begin wait");
objectA.wait();
System.out.println("threadB end wait");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread threadC =new Thread(){
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (objectA){
objectA.notifyAll();
}
}
};
threadA.start();
threadB.start();
threadC.start();
}
}
结果:
threadA begin wait
threadB begin wait
threadB end wait
threadB end wait