Java中 join(long millis)的问题( 二 )

下为修改后代码import java.util.concurrent.CountDownLatch;import java.util.concurrent.LinkedBlockingQueue;/** * Created by XDean on 2016/6/15. */public class TestJoin {\tstatic LinkedBlockingQueue\u0026lt;String\u0026gt; queue = new LinkedBlockingQueue\u0026lt;\u0026gt;();\tstatic CountDownLatch startLatch = new CountDownLatch(1);\tstatic CountDownLatch finishLatch = new CountDownLatch(2);\tstatic long startMillis = System.nanoTime() / 1000 / 1000;\tpublic static void main(String args) throws InterruptedException {\t\tThreadB b = new ThreadB();\t\tThreadA a = new ThreadA(b);\t\ta.start();\t\tb.start();\t\tstartLatch.countDown();\t\tsubmitMsg("JOIN IN");\t\tb.join(2000);\t\tsubmitMsg("JOIN OUT");\t\tfinishLatch.await();\t\tqueue.forEach(System.out::println);\t}\tpublic static void submitMsg(String s) {\t\tlong time = System.nanoTime() / 1000 / 1000 - startMillis;\t\tqueue.add(String.format("%s %s at %d",\t\t\t\tThread.currentThread().getName(), s, time));\t}}class ThreadA extends Thread {\tprivate ThreadB b;\tpublic ThreadA(ThreadB b) {\t\tsuper("Thread-A");\t\tthis.b = b;\t}\t@Override\tpublic void run() {\t\ttry {\t\t\tTestJoin.startLatch.await();\t\t} catch (InterruptedException e) {\t\t\te.printStackTrace();\t\t}\t\tsynchronized (b)\t\t{\t\t\tTestJoin.submitMsg("START");\t\t\ttry {\t\t\t\tThread.sleep(5000);\t\t\t} catch (InterruptedException e) {\t\t\t\te.printStackTrace();\t\t\t}\t\t\tTestJoin.submitMsg("FINISH");\t\t}\t\tTestJoin.finishLatch.countDown();\t}}class ThreadB extends Thread {\tpublic ThreadB() {\t\tsuper("Thread-B");\t}\t@Override\tpublic synchronized void run() {\t\ttry {\t\t\tTestJoin.startLatch.await();\t\t} catch (InterruptedException e) {\t\t\te.printStackTrace();\t\t}\t\t{\t\t\tTestJoin.submitMsg("START");\t\t\ttry {\t\t\t\tThread.sleep(5000);\t\t\t} catch (InterruptedException e) {\t\t\t\te.printStackTrace();\t\t\t}\t\t\tTestJoin.submitMsg("FINISH");\t\t}\t\tTestJoin.finishLatch.countDown();\t}}


推荐阅读