【Java】線程中的wait和notify

來源:互聯網
上載者:User

標籤:java 線程同步

線程中的同步問題通常使用的是synchronized塊,結合wait和notify方法,今天簡單做了一個測試。發現當一個線程鎖定了某個臨界資源後另一個線程會自動等待,以往自己還認為需要自己寫代碼讓其等待呢。。。


共用資源:

package sm.model;import org.apache.log4j.Logger;public class ThreadFuncs {/** * Logger for this class */private static final Logger logger = Logger.getLogger(ThreadFuncs.class);private int shareNum;public ThreadFuncs(int initShareNum){this.shareNum = initShareNum;}public void run1() {if (shareNum < 10) {synchronized (this) {for (; shareNum < 30; shareNum++) {logger.info("I go to print " + shareNum);try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}if (shareNum == 10) {try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}}public void run2() {/*logger.info("I am in run2 " + shareNum);while (shareNum == 0) {try {logger.info("I am in while " + shareNum);Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}*/synchronized (this) {for (; shareNum < 20; shareNum++) {logger.info("print " + shareNum);try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}}this.notify();}}}

線程1:

package sm.examples.threaddemo;import sm.model.ThreadFuncs;public class Thread3_1 extends Thread {private ThreadFuncs funcs;public Thread3_1(ThreadFuncs funcs){this.funcs = funcs;}@Overridepublic void run() {funcs.run1();}}

線程2:

package sm.examples.threaddemo;import sm.model.ThreadFuncs;public class Thread3_2 extends Thread {private ThreadFuncs funcs;public Thread3_2(ThreadFuncs funcs){this.funcs = funcs;}@Overridepublic void run() {funcs.run2();}}

測試類別:

package sm.test;import org.junit.Test;import sm.examples.threaddemo.Thread3_1;import sm.examples.threaddemo.Thread3_2;import sm.model.ThreadFuncs;public class TestThreadWaitNotifyDemo {@Testpublic void test(){ThreadFuncs funcs = new ThreadFuncs(0);Thread t1 = new Thread3_1(funcs);Thread t2 = new Thread3_2(funcs);t1.start();t2.start();try {Thread.sleep(100000);} catch (InterruptedException e) {e.printStackTrace();}}}


【Java】線程中的wait和notify

聯繫我們

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