线程使用完时间片,将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);
-
- }
- }