線程中的同步問題一般使用的是synchronized塊,結合wait和notify方法,今天簡單作了一個測試。發現當一個線程鎖定了某個臨界資源後另外一個線程會自動等待,以往本身還認爲須要本身寫代碼讓其等待呢。。。java
共享資源:apache
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 block e.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 block e.printStackTrace(); } }*/ synchronized (this) { for (; shareNum < 20; shareNum++) { logger.info("print " + shareNum); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } this.notify(); } } }
線程1:ide
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; } @Override public 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; } @Override public void run() { funcs.run2(); } }
測試類:
this
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 { @Test public 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(); } } }