java 線程 原子類相關操作示範範例 thinking in java4 檔案夾21.3.4

來源:互聯網
上載者:User

標籤:main   調優   code   util   調整   thread   extends   mutex   post   

java 線程  原子類相關操作示範範例

package org.rui.thread.volatiles;import java.util.Timer;import java.util.TimerTask;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.atomic.AtomicInteger;/** * 原子類。 * java SE5引入了諸如AtomicInteger AtomicLong AtomicReference * 等特殊的原子性變數類。它們提供以下形式的原子性條件更新操作: *  * boolean compareAndSet(expectedValue,updateValue); *  * 這些類被調整為能夠使用在某些現代處理器上的可獲得的,而且是在機器層級上的原子性。 * 因此在使用它們時。通常不須要操心。對於常規編程來說,它們非常少會派上用場,可是在涉級效能調優時, * 它們就大實用武之地了。比如,我們能夠使用AtomicInteger來重寫AtomictyTest.java * @author lenovo * */public class AtomicIntegerTest implements Runnable {/** * 這裡我們通過使用AtomicInteger而消除了synchronizedkeyword。 * 由於這個程式不會失敗。所以加入了一個timer,以便在5秒鐘之後自己主動地終止 */private AtomicInteger i=new AtomicInteger(0);public int getValue(){return i.get();}private void evenIncrement(){i.addAndGet(2);}@Overridepublic void run() {while(true){evenIncrement();}}public static void main(String[] args) {//訂時器new Timer().schedule(new TimerTask() {@Overridepublic void run() {System.err.println("Aborting");System.exit(0);}}, 5000);//線程池ExecutorService exec=Executors.newCachedThreadPool();AtomicIntegerTest at=new AtomicIntegerTest();exec.execute(at);while(true){int val=at.getValue();if(val%2!=0){System.out.println(val);System.exit(0);}}}}/** * output: * Aborting */

package org.rui.thread.volatiles;import java.util.concurrent.atomic.AtomicInteger;import org.rui.thread.res.EvenChecker;import org.rui.thread.res.IntGenerator;/** * 以下是用AtomicInteger重寫MutexEvenGenerator.java: * 全部其它形式的同步再次通過使用AtomicInteger得到了根除 *  *  *  * 應該強調的是,atomic類被設計用來構建java.util.concureent中的類。 * 因此僅僅有在特殊情況下才在自己的代碼中使用它們,即便使用了也須要確保不存在其它可能出現的問題。

* 通常依賴於鎖要更安全一些(要麼是synchronizedkeyword,要麼是顯式的lock對象) * @author lenovo * */public class AtomicEvenGenerator extends IntGenerator{private AtomicInteger currentEvenValue=new AtomicInteger(0);@Overridepublic int next() {return currentEvenValue.addAndGet(2);}public static void main(String[] args) {EvenChecker.test(new AtomicEvenGenerator());}}



java 線程 原子類相關操作示範範例 thinking in java4 檔案夾21.3.4

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.