Java多線程:線程同步——實驗2__Java

來源:互聯網
上載者:User
原文地址: http://blog.csdn.net/huang_xw/article/details/7318554
/** * @Description: 兩個線程(線程1與線程2)訪問同一個對象的內同步方法syn *  結果: 線程1訪問對象sameObj的同步方法syn()時, 線程2訪問對象sameObj中的同步方法syn()阻塞. 或者線程2訪問時, 線程1阻塞. *  結論: 不同線程訪問同一個對象的相同同步方法時, 線程間是互斥的.  * @author snoopy * @blog http://blog.csdn.net/huang_xw */package basic.b_syn;import org.apache.log4j.Logger;import sun.management.snmp.jvminstr.JvmThreadInstanceEntryImpl.ThreadStateMap;public class TestSynB {private static Logger logger = Logger.getLogger(TestSynB.class);// 線程1static class T1 implements Runnable {TestSynB s;public T1(TestSynB sameObj) {this.s = sameObj;}// 線程1訪問同步方法syn()public void run() {logger.debug("啟動線程1...........");s.syn();logger.debug("退出線程1...........");}}// 線程2static class T2 implements Runnable {TestSynB s;public T2(TestSynB sameObj) {this.s = sameObj;}// 線程2訪問同步方法syn()public void run() {logger.debug("啟動線程2...........");s.syn();logger.debug("退出線程2...........");}}// 對象的同步方法public synchronized void syn() {String threadStr = Thread.currentThread().getName();logger.debug("▲▲▲▲▲▲" + threadStr + "開始訪問同步方法");try {logger.debug(threadStr + "正在訪問同步方法!!!");Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}logger.debug("▲▲▲▲▲▲" + threadStr + "退出同步方法");}public static void main(String[] args) {// 這是多線程要訪問的同一個對象TestSynB sameObj = new TestSynB();// 線程1訪問同步方法syn(), 線程2同樣也訪問同步方法syn().Thread t1 = new Thread(new T1(sameObj), "線程1");Thread t2 = new Thread(new T2(sameObj), "線程2");t1.start();t2.start();}}
執行結果:
0    [線程2] DEBUG basic.b_syn.TestSynB - 啟動線程2...........0    [線程1] DEBUG basic.b_syn.TestSynB - 啟動線程1...........1    [線程2] DEBUG basic.b_syn.TestSynB - ▲▲▲▲▲▲線程2開始訪問同步方法1    [線程2] DEBUG basic.b_syn.TestSynB - 線程2正在訪問同步方法!!!3001 [線程2] DEBUG basic.b_syn.TestSynB - ▲▲▲▲▲▲線程2退出同步方法3001 [線程1] DEBUG basic.b_syn.TestSynB - ▲▲▲▲▲▲線程1開始訪問同步方法3001 [線程1] DEBUG basic.b_syn.TestSynB - 線程1正在訪問同步方法!!!3001 [線程2] DEBUG basic.b_syn.TestSynB - 退出線程2...........6001 [線程1] DEBUG basic.b_syn.TestSynB - ▲▲▲▲▲▲線程1退出同步方法6001 [線程1] DEBUG basic.b_syn.TestSynB - 退出線程1...........


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.