回答

收藏

AQS唤醒后继线程 为什么是从后向前遍历

技术问答 技术问答 735 人阅读 | 0 人回复 | 2023-09-11

    0 i0 ?7 i# P& ?" |# W( r
  •     private void unparkSuccessor(Node node) {
    * w1 E0 W8 t  v# f9 c; ]9 K8 {
  •         /*
    1 @6 x) l, z- l  V0 L  M' E$ N. i
  •          * If status is negative (i.e., possibly needing signal) try& t5 h# W& R, f& {
  •          * to clear in anticipation of signalling.  It is OK if this" B) ?" [( G0 s- D/ e* f- L
  •          * fails or if status is changed by waiting thread.
    & Z* g7 t6 B7 ]1 X
  •          */$ x) D6 X* m% z
  •         int ws = node.waitStatus;" y6 E+ v" Q8 |5 {2 q( ]
  •         if (ws < 0)8 a  P0 z  M$ }
  •             compareAndSetWaitStatus(node, ws, 0);  b( O$ m/ q0 M7 h  b

  • 5 Q; J0 p, P/ T. ^( g: V: p; A% s
  •         /*3 y% ~: ?4 C  G5 y6 c
  •          * Thread to unpark is held in successor, which is normally, U# H1 |& ?. j0 S& U8 p2 p: w  C
  •          * just the next node.  But if cancelled or apparently null,
    $ p: E! C# ?- o# Z; Q. e
  •          * traverse backwards from tail to find the actual) n  F! \: l0 Q0 B
  •          * non-cancelled successor.
    # _2 p* ]) R; S5 d
  •          */
    ' b' x5 m) ^. w$ s7 Z; |
  •         Node s = node.next;  ?# z+ D4 U/ |* w3 [% C0 y
  •         if (s == null || s.waitStatus > 0) {( Z) Q$ u$ b! ^- y$ h4 p+ Y; R
  •             s = null;. R4 C( x" b7 |, ]( \% P' _; R
  •             for (Node t = tail; t != null && t != node; t = t.prev)0 u: `9 C" t* h  K- A# p$ ^' M; C' e
  •                 if (t.waitStatus <= 0)  B* X# v/ P- r  ~1 j( @
  •                     s = t;
    6 k( @( w# J3 Z& ^
  •         }2 F1 E" A! N, }- B2 P+ c9 t
  •         if (s != null)1 K! Q3 C( M" c) m. m4 R( y- O" F
  •             LockSupport.unpark(s.thread);    }
    7 D  P* P2 ?: v4 j
如果没有合法的数据,从后向前遍历,为什么这么做呢?从前向后不行吗?
. w/ Y1 d# Y' ]2 G
7 B% T8 m" Y' M           lgd1152已获得悬赏 5 金钱最佳答案' o. R2 Z3 @; d" K- ?1 b

9 f4 b3 I/ i8 P$ J  ?              因为从前往后会遇到空指针               7 x6 ^6 L0 |$ A3 {
            - N# Y6 V# |( @, ~) C
  • lgd1152        % l2 c- U1 [9 }5 @  z( |1 u
  • 发表于2022-01-15        
    ! b2 B9 }+ G) c
  • 详细答案 >   
    9 O6 c! Y2 `' u$ s, e+ n" V

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则