﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>BlogJava-jinfeng_wang-随笔分类-2016-thread</title><link>http://www.blogjava.net/jinfeng_wang/category/55142.html</link><description>G-G-S,D-D-U!</description><language>zh-cn</language><lastBuildDate>Wed, 14 Dec 2016 13:27:19 GMT</lastBuildDate><pubDate>Wed, 14 Dec 2016 13:27:19 GMT</pubDate><ttl>60</ttl><item><title>JVM GC</title><link>http://www.blogjava.net/jinfeng_wang/archive/2016/12/14/432095.html</link><dc:creator>jinfeng_wang</dc:creator><author>jinfeng_wang</author><pubDate>Wed, 14 Dec 2016 08:06:00 GMT</pubDate><guid>http://www.blogjava.net/jinfeng_wang/archive/2016/12/14/432095.html</guid><wfw:comment>http://www.blogjava.net/jinfeng_wang/comments/432095.html</wfw:comment><comments>http://www.blogjava.net/jinfeng_wang/archive/2016/12/14/432095.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/jinfeng_wang/comments/commentRss/432095.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/jinfeng_wang/services/trackbacks/432095.html</trackback:ping><description><![CDATA[&nbsp;&nbsp;&nbsp;&nbsp; 摘要: http://zqhxuyuan.github.io/2016/07/26/JVM/JVM架构当一个程序启动之前，它的class会被类装载器装入方法区(Permanent区)，执行引擎读取方法区的字节码自适应解析，边解析边运行，然后pc寄存器指向了main函数所在位置，虚拟机开始为main函数在Java栈中预留一个栈帧（每个方法都对应一个栈帧），然后开始跑main函数，main函数里的代码被执行引...&nbsp;&nbsp;<a href='http://www.blogjava.net/jinfeng_wang/archive/2016/12/14/432095.html'>阅读全文</a><img src ="http://www.blogjava.net/jinfeng_wang/aggbug/432095.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/jinfeng_wang/" target="_blank">jinfeng_wang</a> 2016-12-14 16:06 <a href="http://www.blogjava.net/jinfeng_wang/archive/2016/12/14/432095.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Synchronized与Lock锁的区别</title><link>http://www.blogjava.net/jinfeng_wang/archive/2016/12/14/432090.html</link><dc:creator>jinfeng_wang</dc:creator><author>jinfeng_wang</author><pubDate>Wed, 14 Dec 2016 06:26:00 GMT</pubDate><guid>http://www.blogjava.net/jinfeng_wang/archive/2016/12/14/432090.html</guid><wfw:comment>http://www.blogjava.net/jinfeng_wang/comments/432090.html</wfw:comment><comments>http://www.blogjava.net/jinfeng_wang/archive/2016/12/14/432090.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/jinfeng_wang/comments/commentRss/432090.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/jinfeng_wang/services/trackbacks/432090.html</trackback:ping><description><![CDATA[<div>http://www.tuicool.com/articles/2aeUBfe<br /><br /><h2>楔子</h2><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">最近一直都比较忙，没有时间写博客了。今天项目终于灰度了，可以有时间写写博客，看看文章了！！！&#9582;(&#9583;&#9661;&#9584;)&#9581;</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">今天要写的主题是Java的基础知识，Synchronized和Lock锁的区别！！！</p><h2>区别</h2><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">1、ReentrantLock拥有Synchronized相同的并发性和内存语义，此外还多了 锁投票，定时锁等候和中断锁等候等特性。</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">线程A和B都要获取对象O的锁定，假设A获取了对象O锁，B将等待A释放对O的锁定</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">如果使用 synchronized ，如果A不释放，B将一直等下去，不能被中断</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">如果 使用ReentrantLock，如果A不释放，可以使B在等待了足够长的时间以后，中断等待，而干别的事情</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">ReentrantLock获取锁定与三种方式：</p><ul style="padding: 0px; margin: 0px 0px 0.75em 25px; list-style-type: none; font-size: 16px; line-height: 27.2px; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;"><li style="line-height: 1.7em; list-style-type: disc;"><p style="margin: 0px 0px 0.75em; line-height: 1.7em;">lock(), 如果获取了锁立即返回，如果别的线程持有锁，当前线程则一直处于休眠状态，直到获取锁</p></li><li style="line-height: 1.7em; list-style-type: disc;"><p style="margin: 0px 0px 0.75em; line-height: 1.7em;">tryLock(), 如果获取了锁立即返回true，如果别的线程正持有锁，立即返回false；</p></li><li style="line-height: 1.7em; list-style-type: disc;"><p style="margin: 0px 0px 0.75em; line-height: 1.7em;">tryLock(long timeout,TimeUnit unit)， 如果获取了锁定立即返回true，如果别的线程正持有锁，会等待参数给定的时间，在等待的过程中，如果获取了锁定，就返回true，如果等待超时，返回false；</p></li><li style="line-height: 1.7em; list-style-type: disc;"><p style="margin: 0px 0px 0.75em; line-height: 1.7em;">lockInterruptibly:如果获取了锁定立即返回，如果没有获取锁定，当前线程处于休眠状态，直到或者锁定，或者当前线程被别的线程中断</p></li></ul><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">2、synchronized是在JVM层面上实现的，不但可以通过一些监控工具监控synchronized的锁定，而且在代码执行时出现异常，JVM会自动释放锁定，但是使用Lock则不行，lock是通过代码实现的，要保证锁定一定会被释放，就必须将unLock()放到finally{}中</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">3、在资源竞争不是很激烈的情况下，Synchronized的性能要优于ReetrantLock，但是在资源竞争很激烈的情况下，Synchronized的性能会下降几十倍，但是ReetrantLock的性能能维持常态；</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">5.0的多线程任务包对于同步的性能方面有了很大的改进，在原有synchronized关键字的基础上，又增加了ReentrantLock，以及各种Atomic类。了解其性能的优劣程度，有助与我们在特定的情形下做出正确的选择。</p><h2>简单的总结</h2><ul style="padding: 0px; margin: 0px 0px 0.75em 25px; list-style-type: none; font-size: 16px; line-height: 27.2px; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;"><li style="line-height: 1.7em; list-style-type: disc;"><p style="margin: 0px 0px 0.75em; line-height: 1.7em;">synchronized：</p><p style="margin: 0px 0px 0.75em; line-height: 1.7em;">在资源竞争不是很激烈的情况下，偶尔会有同步的情形下，synchronized是很合适的。原因在于，编译程序通常会尽可能的进行优化synchronize，另外可读性非常好，不管用没用过5.0多线程包的程序员都能理解。</p></li><li style="line-height: 1.7em; list-style-type: disc;"><p style="margin: 0px 0px 0.75em; line-height: 1.7em;">ReentrantLock:</p><p style="margin: 0px 0px 0.75em; line-height: 1.7em;">ReentrantLock提供了多样化的同步，比如有时间限制的同步，可以被Interrupt的同步（synchronized的同步是不能Interrupt的）等。在资源竞争不激烈的情形下，性能稍微比synchronized差点点。但是当同步非常激烈的时候，synchronized的性能一下子能下降好几十倍。而ReentrantLock确还能维持常态。</p></li><li style="line-height: 1.7em; list-style-type: disc;"><p style="margin: 0px 0px 0.75em; line-height: 1.7em;">Atomic:</p><p style="margin: 0px 0px 0.75em; line-height: 1.7em;">和上面的类似，不激烈情况下，性能比synchronized略逊，而激烈的时候，也能维持常态。激烈的时候，Atomic的性能会优于ReentrantLock一倍左右。但是其有一个缺点，就是只能同步一个值，一段代码中只能出现一个Atomic的变量，多于一个同步无效。因为他不能在多个Atomic之间同步。</p></li></ul><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">所以，我们写同步的时候，优先考虑synchronized，如果有特殊需要，再进一步优化。ReentrantLock和Atomic如果用的不好，不仅不能提高性能，还可能带来灾难。</p><h2>测试结果</h2><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">先贴测试结果：再贴代码（Atomic测试代码不准确，一个同步中只能有1个Actomic，这里用了2个，但是这里的测试只看速度）</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">round:100000 thread:5</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">Sync = 35301694</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">Lock = 56255753</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">Atom = 43467535</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">round:200000 thread:10</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">Sync = 110514604</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">Lock = 204235455</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">Atom = 170535361</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">round:300000 thread:15</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">Sync = 253123791</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">Lock = 448577123</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">Atom = 362797227</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">round:400000 thread:20</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">Sync = 16562148262</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">Lock = 846454786</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">Atom = 667947183</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">round:500000 thread:25</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">Sync = 26932301731</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">Lock = 1273354016</p><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">Atom = 982564544</p><h2>Java代码</h2><pre hljs=""  java"="" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; color: #444444; border-radius: 4px; margin-top: 0px; margin-bottom: 1.5em; line-height: 1.5em; word-break: break-all; word-wrap: break-word; border: none; overflow-x: auto; background-color: #f6f6f6;"><span style="color: #333333; font-weight: 700;">package</span> test.thread;       <span style="color: #333333; font-weight: 700;">import</span> <span style="color: #333333; font-weight: 700;">static</span> java.lang.System.out;       <span style="color: #333333; font-weight: 700;">import</span> java.util.Random;      <span style="color: #333333; font-weight: 700;">import</span> java.util.concurrent.BrokenBarrierException;      <span style="color: #333333; font-weight: 700;">import</span> java.util.concurrent.CyclicBarrier;      <span style="color: #333333; font-weight: 700;">import</span> java.util.concurrent.ExecutorService;      <span style="color: #333333; font-weight: 700;">import</span> java.util.concurrent.Executors;      <span style="color: #333333; font-weight: 700;">import</span> java.util.concurrent.atomic.AtomicInteger;      <span style="color: #333333; font-weight: 700;">import</span> java.util.concurrent.atomic.AtomicLong;      <span style="color: #333333; font-weight: 700;">import</span> java.util.concurrent.locks.ReentrantLock;       <span style="color: #333333; font-weight: 700;">public</span> <span style="color: #333333; font-weight: 700;">class <span style="color: #880000;">TestSyncMethods</span> </span>{           <span style="color: #333333; font-weight: 700;">public static void <span style="color: #880000;">test</span>(int round,int threadNum,CyclicBarrier cyclicBarrier)</span>{              <span style="color: #333333; font-weight: 700;">new</span> SyncTest(<span style="color: #880000;">"Sync"</span>,round,threadNum,cyclicBarrier).testTime();              <span style="color: #333333; font-weight: 700;">new</span> LockTest(<span style="color: #880000;">"Lock"</span>,round,threadNum,cyclicBarrier).testTime();              <span style="color: #333333; font-weight: 700;">new</span> AtomicTest(<span style="color: #880000;">"Atom"</span>,round,threadNum,cyclicBarrier).testTime();          }           <span style="color: #333333; font-weight: 700;">public static void <span style="color: #880000;">main</span>(String args[])</span>{               <span style="color: #333333; font-weight: 700;">for</span>(<span style="color: #333333; font-weight: 700;">int</span> i=<span style="color: #880000;">0</span>;i&lt;<span style="color: #880000;">5</span>;i++){                  <span style="color: #333333; font-weight: 700;">int</span> round=<span style="color: #880000;">100000</span>*(i+<span style="color: #880000;">1</span>);                  <span style="color: #333333; font-weight: 700;">int</span> threadNum=<span style="color: #880000;">5</span>*(i+<span style="color: #880000;">1</span>);                  CyclicBarrier cb=<span style="color: #333333; font-weight: 700;">new</span> CyclicBarrier(threadNum*<span style="color: #880000;">2</span>+<span style="color: #880000;">1</span>);                  out.println(<span style="color: #880000;">"=========================="</span>);                  out.println(<span style="color: #880000;">"round:"</span>+round+<span style="color: #880000;">" thread:"</span>+threadNum);                  test(round,threadNum,cb);               }          }      }       <span style="color: #333333; font-weight: 700;">class <span style="color: #880000;">SyncTest</span> extends <span style="color: #880000;">TestTemplate</span></span>{          <span style="color: #333333; font-weight: 700;">public <span style="color: #880000;">SyncTest</span>(String _id,int _round,int _threadNum,CyclicBarrier _cb)</span>{              <span style="color: #333333; font-weight: 700;">super</span>( _id, _round, _threadNum, _cb);          }          <span style="color: #1f7199;">@Override</span>         <span style="color: #888888;">/**         * synchronized关键字不在方法签名里面，所以不涉及重载问题         */</span>         <span style="color: #333333; font-weight: 700;">synchronized long  <span style="color: #880000;">getValue</span>() </span>{              <span style="color: #333333; font-weight: 700;">return</span> <span style="color: #333333; font-weight: 700;">super</span>.countValue;          }          <span style="color: #1f7199;">@Override</span>         <span style="color: #333333; font-weight: 700;">synchronized void  <span style="color: #880000;">sumValue</span>() </span>{              <span style="color: #333333; font-weight: 700;">super</span>.countValue+=preInit[index++%round];          }      }        <span style="color: #333333; font-weight: 700;">class <span style="color: #880000;">LockTest</span> extends <span style="color: #880000;">TestTemplate</span></span>{          ReentrantLock lock=<span style="color: #333333; font-weight: 700;">new</span> ReentrantLock();          <span style="color: #333333; font-weight: 700;">public <span style="color: #880000;">LockTest</span>(String _id,int _round,int _threadNum,CyclicBarrier _cb)</span>{              <span style="color: #333333; font-weight: 700;">super</span>( _id, _round, _threadNum, _cb);          }          <span style="color: #888888;">/**         * synchronized关键字不在方法签名里面，所以不涉及重载问题         */</span>         <span style="color: #1f7199;">@Override</span>         <span style="color: #333333; font-weight: 700;">long <span style="color: #880000;">getValue</span>() </span>{              <span style="color: #333333; font-weight: 700;">try</span>{                  lock.lock();                  <span style="color: #333333; font-weight: 700;">return</span> <span style="color: #333333; font-weight: 700;">super</span>.countValue;              }<span style="color: #333333; font-weight: 700;">finally</span>{                  lock.unlock();              }          }          <span style="color: #1f7199;">@Override</span>         <span style="color: #333333; font-weight: 700;">void <span style="color: #880000;">sumValue</span>() </span>{              <span style="color: #333333; font-weight: 700;">try</span>{                  lock.lock();                  <span style="color: #333333; font-weight: 700;">super</span>.countValue+=preInit[index++%round];              }<span style="color: #333333; font-weight: 700;">finally</span>{                  lock.unlock();              }          }      }        <span style="color: #333333; font-weight: 700;">class <span style="color: #880000;">AtomicTest</span> extends <span style="color: #880000;">TestTemplate</span></span>{          <span style="color: #333333; font-weight: 700;">public <span style="color: #880000;">AtomicTest</span>(String _id,int _round,int _threadNum,CyclicBarrier _cb)</span>{              <span style="color: #333333; font-weight: 700;">super</span>( _id, _round, _threadNum, _cb);          }          <span style="color: #1f7199;">@Override</span>         <span style="color: #888888;">/**         * synchronized关键字不在方法签名里面，所以不涉及重载问题         */</span>         <span style="color: #333333; font-weight: 700;">long  <span style="color: #880000;">getValue</span>() </span>{              <span style="color: #333333; font-weight: 700;">return</span> <span style="color: #333333; font-weight: 700;">super</span>.countValueAtmoic.get();          }          <span style="color: #1f7199;">@Override</span>         <span style="color: #333333; font-weight: 700;">void  <span style="color: #880000;">sumValue</span>() </span>{              <span style="color: #333333; font-weight: 700;">super</span>.countValueAtmoic.addAndGet(<span style="color: #333333; font-weight: 700;">super</span>.preInit[indexAtomic.get()%round]);          }      }      <span style="color: #333333; font-weight: 700;">abstract</span> <span style="color: #333333; font-weight: 700;">class <span style="color: #880000;">TestTemplate</span></span>{          <span style="color: #333333; font-weight: 700;">private</span> String id;          <span style="color: #333333; font-weight: 700;">protected</span> <span style="color: #333333; font-weight: 700;">int</span> round;          <span style="color: #333333; font-weight: 700;">private</span> <span style="color: #333333; font-weight: 700;">int</span> threadNum;          <span style="color: #333333; font-weight: 700;">protected</span> <span style="color: #333333; font-weight: 700;">long</span> countValue;          <span style="color: #333333; font-weight: 700;">protected</span> AtomicLong countValueAtmoic=<span style="color: #333333; font-weight: 700;">new</span> AtomicLong(<span style="color: #880000;">0</span>);          <span style="color: #333333; font-weight: 700;">protected</span> <span style="color: #333333; font-weight: 700;">int</span>[] preInit;          <span style="color: #333333; font-weight: 700;">protected</span> <span style="color: #333333; font-weight: 700;">int</span> index;          <span style="color: #333333; font-weight: 700;">protected</span> AtomicInteger indexAtomic=<span style="color: #333333; font-weight: 700;">new</span> AtomicInteger(<span style="color: #880000;">0</span>);          Random r=<span style="color: #333333; font-weight: 700;">new</span> Random(<span style="color: #880000;">47</span>);          <span style="color: #888888;">//任务栅栏，同批任务，先到达wait的任务挂起，一直等到全部任务到达制定的wait地点后，才能全部唤醒，继续执行     </span>     <span style="color: #333333; font-weight: 700;">private</span> CyclicBarrier cb;          <span style="color: #333333; font-weight: 700;">public <span style="color: #880000;">TestTemplate</span>(String _id,int _round,int _threadNum,CyclicBarrier _cb)</span>{              <span style="color: #333333; font-weight: 700;">this</span>.id=_id;              <span style="color: #333333; font-weight: 700;">this</span>.round=_round;              <span style="color: #333333; font-weight: 700;">this</span>.threadNum=_threadNum;              cb=_cb;              preInit=<span style="color: #333333; font-weight: 700;">new</span> <span style="color: #333333; font-weight: 700;">int</span>[round];              <span style="color: #333333; font-weight: 700;">for</span>(<span style="color: #333333; font-weight: 700;">int</span> i=<span style="color: #880000;">0</span>;i&lt;preInit.length;i++){                  preInit[i]=r.nextInt(<span style="color: #880000;">100</span>);              }          }           <span style="color: #333333; font-weight: 700;">abstract void <span style="color: #880000;">sumValue</span>()</span>;          <span style="color: #888888;">/*         * 对long的操作是非原子的，原子操作只针对32位         * long是64位，底层操作的时候分2个32位读写，因此不是线程安全         */</span>         <span style="color: #333333; font-weight: 700;">abstract long <span style="color: #880000;">getValue</span>()</span>;           <span style="color: #333333; font-weight: 700;">public void <span style="color: #880000;">testTime</span>()</span>{              ExecutorService se=Executors.newCachedThreadPool();              <span style="color: #333333; font-weight: 700;">long</span> start=System.nanoTime();              <span style="color: #888888;">//同时开启2*ThreadNum个数的读写线程     </span>         <span style="color: #333333; font-weight: 700;">for</span>(<span style="color: #333333; font-weight: 700;">int</span> i=<span style="color: #880000;">0</span>;i&lt;threadNum;i++){                  se.execute(<span style="color: #333333; font-weight: 700;">new</span> Runnable(){                      <span style="color: #333333; font-weight: 700;">public void <span style="color: #880000;">run</span>() </span>{                          <span style="color: #333333; font-weight: 700;">for</span>(<span style="color: #333333; font-weight: 700;">int</span> i=<span style="color: #880000;">0</span>;i&lt;round;i++){                              sumValue();                          }                           <span style="color: #888888;">//每个线程执行完同步方法后就等待     </span>                     <span style="color: #333333; font-weight: 700;">try</span> {                              cb.await();                          } <span style="color: #333333; font-weight: 700;">catch</span> (InterruptedException e) {                              <span style="color: #888888;">// TODO Auto-generated catch block     </span>                         e.printStackTrace();                          } <span style="color: #333333; font-weight: 700;">catch</span> (BrokenBarrierException e) {                              <span style="color: #888888;">// TODO Auto-generated catch block     </span>                         e.printStackTrace();                          }                        }                  });                  se.execute(<span style="color: #333333; font-weight: 700;">new</span> Runnable(){                      <span style="color: #333333; font-weight: 700;">public void <span style="color: #880000;">run</span>() </span>{                           getValue();                          <span style="color: #333333; font-weight: 700;">try</span> {                              <span style="color: #888888;">//每个线程执行完同步方法后就等待     </span>                         cb.await();                          } <span style="color: #333333; font-weight: 700;">catch</span> (InterruptedException e) {                              <span style="color: #888888;">// TODO Auto-generated catch block     </span>                         e.printStackTrace();                          } <span style="color: #333333; font-weight: 700;">catch</span> (BrokenBarrierException e) {                              <span style="color: #888888;">// TODO Auto-generated catch block     </span>                         e.printStackTrace();                          }                       }                  });              }               <span style="color: #333333; font-weight: 700;">try</span> {                  <span style="color: #888888;">//当前统计线程也wait,所以CyclicBarrier的初始值是threadNum*2+1     </span>             cb.await();              } <span style="color: #333333; font-weight: 700;">catch</span> (InterruptedException e) {                  <span style="color: #888888;">// TODO Auto-generated catch block     </span>             e.printStackTrace();              } <span style="color: #333333; font-weight: 700;">catch</span> (BrokenBarrierException e) {                  <span style="color: #888888;">// TODO Auto-generated catch block     </span>             e.printStackTrace();              }              <span style="color: #888888;">//所有线程执行完成之后，才会跑到这一步     </span>         <span style="color: #333333; font-weight: 700;">long</span> duration=System.nanoTime()-start;              out.println(id+<span style="color: #880000;">" = "</span>+duration);           }       }</pre><h2>补充知识</h2><p style="margin: 0px 0px 0.75em; font-size: 16px; line-height: 27.2px; text-indent: 1em; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;">CyclicBarrier和CountDownLatch一样，都是关于线程的计数器。</p><ul style="padding: 0px; margin: 0px 0px 0.75em 25px; list-style-type: none; font-size: 16px; line-height: 27.2px; color: #333333; font-family: 'Helvetica Neue', Helvetica, Tahoma, Arial, STXihei, 'Microsoft YaHei', 微软雅黑, sans-serif; background-color: #fefefe;"><li style="line-height: 1.7em; list-style-type: disc;">CyclicBarrier初始化时规定一个数目，然后计算调用了CyclicBarrier.await()进入等待的线程数。当线程数达到了这个数目时，所有进入等待状态的线程被唤醒并继续。</li><li style="line-height: 1.7em; list-style-type: disc;">CyclicBarrier就象它名字的意思一样，可看成是个障碍， 所有的线程必须到齐后才能一起通过这个障碍。</li><li style="line-height: 1.7em; list-style-type: disc;">CyclicBarrier初始时还可带一个Runnable的参数， 此Runnable任务在CyclicBarrier的数目达到后，所有其它线程被唤醒前被执行。</li></ul></div><img src ="http://www.blogjava.net/jinfeng_wang/aggbug/432090.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/jinfeng_wang/" target="_blank">jinfeng_wang</a> 2016-12-14 14:26 <a href="http://www.blogjava.net/jinfeng_wang/archive/2016/12/14/432090.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>