java活锁测试



package test.thread;

public class TestLiveLock {
 public static void main(String[] args) {
  Person talong = new Person("talong");
  Person sharon = new Person("sharon");
  talong.friend = sharon;
  sharon.friend = talong;
  talong.bow();
  new Thread(sharon).start();
  new Thread(talong).start();
 }
}
class Person implements Runnable {
 Person friend;
 String name;
 public Person(String name){
  this.name=name;
 }
 boolean bow = false;
 public void bow() {
  System.out.println(name+" bow");
  bow = true;
 }
 public void up() {
  System.out.println(name+" up");
  bow = false;
 }
 public void run() {
  while (friend.bow) {
   this.bow();
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   this.up();
  }
 }
}


运行结果:

talong bow
sharon bow
talong bow
talong up
talong bow
sharon up
sharon bow
talong up
sharon up
sharon bow
talong bow
sharon up
sharon bow
talong up
talong bow
sharon up
sharon bow
talong up
talong bow
sharon up

。。。


如果将睡眠时间调整为10毫秒,则活锁可能很快就能解开

你可能感兴趣的:(java,活锁)