標籤: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