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}}
推荐阅读
- dart这编程语言现在发展怎么样了,语法与Java,c#很相似,甚至更简洁
- Java工程师和C++工程师在工作上有啥区别哪个更适合自身发展
- 27岁,转行java的血与泪,该何去何从
- 怎样统计工程中未使用的java类
- 新互联网网站用Java还靠谱么对比Php,Python,Ruby的话
- 我想学java和安卓软件开发?
- 学计算机专业,java那些和网站开发选台式还是笔记本好
- JAVA设计思路
- 本人大专毕业一年,想要去培训,定了JAVAEE和安卓两个方向,应该学那个纠结,求帮助
- 从未接触过软件测试和java,可以学习主要是自学这两种其一吗
