LJXColin
2021-02-11 17:23
采纳率: 100%
浏览 36
已采纳

请教大牛,举个活锁的例子,活锁是否在单线程或多线程下都可发生?活锁与死循环有什么区别?

活锁在于线程是“活”的,不阻塞,但却一直忙碌不能完成线程生命周期。有几个疑惑想请教下大家,活锁的发生是否一定需要上锁(synchronized或lock),活锁的demo一般基于不断重试(while(true)或for(;;)),因此个人又认为活锁与死循环类似。请问下大家的理解是怎么样的?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • allway2 2021-02-11 22:45
    已采纳
    package DeadlockLivelock;
    
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    public class Livelock {
    	public static void main(String[] args) {
    		Livelock livelock = new Livelock();
    		new Thread(livelock::action1).start();
    		new Thread(livelock::action2).start();
    	}
    
    	private Lock lock1 = new ReentrantLock(true);
    	private Lock lock2 = new ReentrantLock(true);
    
    	public void action1() {
    		try {
    			while (true) {
    				lock1.tryLock(50, TimeUnit.MILLISECONDS);
    				System.out.println("LOCK 1 ACQUIRED");
    				TimeUnit.MILLISECONDS.sleep(1000);
    
    				if (lock2.tryLock()) {
    					System.out.println("LOCK 2 ACQUIRED");
    				} else {
    					System.out.println("CANNOT ACQUIRE LOCK 2, RELEASING LOCK 1");
    					lock1.unlock();
    					continue;
    				}
    
    				System.out.println("ACTION 1");
    				break;
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			lock1.unlock();
    			lock2.unlock();
    		}
    	}
    
    	public void action2() {
    		try {
    			while (true) {
    				lock2.tryLock(50, TimeUnit.MILLISECONDS);
    				System.out.println("LOCK 2 ACQUIRED");
    				TimeUnit.MILLISECONDS.sleep(50);
    
    				if (lock1.tryLock()) {
    					System.out.println("LOCK 1 ACQUIRED");
    				} else {
    					System.out.println("CANNOT ACQUIRE LOCK 1, RELEASING LOCK 2");
    					lock2.unlock();
    					continue;
    				}
    
    				System.out.println("ACTION 2");
    				break;
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			lock1.unlock();
    			lock2.unlock();
    		}
    	}
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题