电商网站开发数据库设计,企业如何应用网站的,商汇通网站,陕西网站建设技术方案文章目录 线程活跃性死锁活锁解饿 线程活跃性
死锁
两个线程相互等待对方已拥有的锁#xff0c;就会相互一直等待#xff0c;不会停止。
t1拥有a锁#xff0c;等待b锁。 t2拥有b锁#xff0c;等待a锁。
Slf4j(topic c.Test3)
public class st3 {public st… 文章目录 线程活跃性死锁活锁解饿 线程活跃性
死锁
两个线程相互等待对方已拥有的锁就会相互一直等待不会停止。
t1拥有a锁等待b锁。 t2拥有b锁等待a锁。
Slf4j(topic c.Test3)
public class st3 {public static void main(String[] args) throws InterruptedException {Object A new Object();Object B new Object();Thread t1 new Thread(() - {synchronized (A) {log.debug(lock A);try {sleep(1);} catch (InterruptedException e) {e.printStackTrace();}synchronized (B) {log.debug(lock B);log.debug(操作...);}}}, t1);Thread t2 new Thread(() - {synchronized (B) {log.debug(lock B);try {sleep(1);} catch (InterruptedException e) {e.printStackTrace();}synchronized (A) {log.debug(lock A);log.debug(操作...);}}}, t2);t1.start();t2.start();}
}活锁
相互改变对方的结束条件两个线程永远无法结束。
count初始为10, t1希望count减到0结束。 t2希望count加到20结束。 两个一起同速度执行一定不能结束。
public class Test3{static volatile int count 10;static final Object lock new Object();public static void main(String[] args) {new Thread(() - {// 期望减到 0 退出循环while (count 0) {sleep(0.2);count--;log.debug(count: {}, count);}}, t1).start();new Thread(() - {// 期望超过 20 退出循环while (count 20) {sleep(0.2);count;log.debug(count: {}, count);}}, t2).start();}
}可以设置两个线程随机的睡眠时间解决。
解饿
线程一直无法获得cpu的调度我么就称为线程饥饿。 可能原因为线程优先级太低。