回答

收藏

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

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


    # J' V! i( f/ L- n) G
  •     private void unparkSuccessor(Node node) {
    + X3 F7 H/ t9 Q3 U
  •         /*
    % n! P1 l5 g% p, J  f6 a
  •          * If status is negative (i.e., possibly needing signal) try" N% {8 Z; n# [) o& J! w
  •          * to clear in anticipation of signalling.  It is OK if this8 @% r" @5 F" `4 Z% K$ t
  •          * fails or if status is changed by waiting thread.
    3 {, F9 u( z3 i# r8 m6 J- i3 \: d$ D
  •          */; P; l- F! ~1 v) I( X% Y
  •         int ws = node.waitStatus;( O' i( H5 h9 N9 p1 R6 u
  •         if (ws < 0)) Z1 }! A1 U" V1 q# `* c
  •             compareAndSetWaitStatus(node, ws, 0);& @" C. s& t% q! F' Y8 M9 Q$ B

  • 7 i3 B, x6 |! u$ c
  •         /*9 N1 b8 [2 _3 H5 n* Y' G% h- O! w2 c9 X
  •          * Thread to unpark is held in successor, which is normally/ L) @& |& O" L4 ^' \% Z% o+ O
  •          * just the next node.  But if cancelled or apparently null,5 f2 K  Y, B+ S) A) Y, W" N
  •          * traverse backwards from tail to find the actual
    5 {$ ]1 H( |: ]' T
  •          * non-cancelled successor.+ r7 s- ^+ V0 d, E% i  h
  •          */
    0 U. H: E0 r* e/ J" @) i; _2 j' ]
  •         Node s = node.next;8 m# Q+ n, r' q5 d. a0 j
  •         if (s == null || s.waitStatus > 0) {
    1 ~" A. K5 d9 g; G+ s# ?
  •             s = null;! n* e/ X+ B* s& [
  •             for (Node t = tail; t != null && t != node; t = t.prev)
    - Z/ y7 |- P0 c9 `; W, T
  •                 if (t.waitStatus <= 0)
    / B. W6 Y) i  ~8 o0 n" B
  •                     s = t;- O' ]% @: s% K: Z1 R+ I+ a' l
  •         }
    ( @9 c. B# F5 s( g$ [
  •         if (s != null)9 \8 f. c0 G, p6 i' l
  •             LockSupport.unpark(s.thread);    }; H) P& w# e% \
如果没有合法的数据,从后向前遍历,为什么这么做呢?从前向后不行吗?3 ]$ S  k0 p$ k) @% Q" s' P
: A% t* n- y( I
           lgd1152已获得悬赏 5 金钱最佳答案
$ |! K6 L- r% r% @% ~, \, f! m/ E& [8 B0 U2 @3 r8 S6 B' g
              因为从前往后会遇到空指针               5 V1 j- X* o( k' e
            & ]/ b. e( X* w- }8 \' F8 n
  • lgd1152        
    $ a; g# Z2 u- P3 L1 T
  • 发表于2022-01-15        
    6 b3 P3 K# C: M+ l! l1 I
  • 详细答案 >   
    $ L3 T. q, t3 l! [, R; r+ c& D2 s

本帖子中包含更多资源

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

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

本版积分规则