上下文切换:
线程使用完时间片,将cpu资源让给其他线程
线程死锁:两个或以上线程,因争夺资源而相互等待的现象
产生死锁条件:
- 互斥条件:资源同一时刻只能被同一线程占用
- 请求并持有条件:线程已持有资源,又需要其他资源,得不到又不释放已有资源
- 不可剥夺条件:资源在自己使用完之前,不能被其他线程占用
- 环路等待条件:资源-线程,形成环形链
案例:资源-线程,形成环形链
演示产生死锁
package deadLockP;
public class DeadLockL {
private final static Object resourceA = new Object();
private final static Object resourceB = new Object();
public static void main(String[] args) {
Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("threadA get resourceA");
synchronized (resourceA) {
try {
Thread.sleep(1000);
System.out.println("threadA try to get resourceB");
synchronized (resourceB) {
System.out.println("threadA get resourceB");
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
});
Thread threadB = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("threadB get resourceB");
synchronized (resourceB) {
try {
Thread.sleep(1000);
System.out.println("threadB try to get resourceA");
synchronized (resourceA) {
System.out.println("threadB get resourceA");
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
});
threadA.start();
threadB.start();
}
}
result:
解决:
线程B也改为获取资源A,B的顺序
避免死锁:
- 破坏请求并持有条件
- 破坏环路等待条件
守护线程与用户线程
举例 | JVM退出 | |
用户线程 | main线程 | 需要等待所有用户线程结束 |
守护线程 | 垃圾回收线程 | 不考虑守护线程是否结束 |
如何设置线程为守护线程(自己默认创建为用户线程)
/**
* 设置为守护线程
*/
public class DemonTest {
public static void main(String[] args) {
Thread daemonThread = new Thread(new Runnable() {
@Override
public void run() {
}
});
// 设置为守护线程
daemonThread.setDaemon(true);
}
}