Java多线程-Liveness
Liveness problems:deadlock,starvation and livelock
Deadlock
Deadlock描述的是两个或多个线程被永远block住,彼此等待的情况。
package mthread; public class Deadlock { static class Friend { private final String name; public Friend(String name) { this.name = name; } public String getName() { return this.name; } public synchronized void bow(Friend bower) { System.out.format("%s: %s" + " has bowed to me!%n", this.name, bower.getName()); bower.bowBack(this); } public synchronized void bowBack(Friend bower) { System.out.format("%s: %s" + " has bowed back to me!%n", this.name, bower.getName()); } } public static void main(String[] args) { final Friend alphonse = new Friend("Alphonse"); final Friend gaston = new Friend("Gaston"); new Thread(new Runnable() { public void run() { alphonse.bow(gaston); } }).start(); new Thread(new Runnable() { public void run() { gaston.bow(alphonse); } }).start(); } }
Starvation
Starvation描述了当一个线程不能正常访问共享资源以至于不能继续执行下去的情况。例如,一个对象的同步方法需要执行很长一段时间才能返回,如果一个线程经常调用它,其它线程同步访问这个对象会被block
Livelock
活锁不同于死锁,活锁没有被block住,但是他们都忙于回应其它的线程而不能继续下去