Synchronization problems in threads usually use the synchronized block, combined with the wait and notify methods, to do a simple test today. It is found that when a thread locks a critical resource, another thread waits for it, and in the past thinks it needs to write its own code to wait for it ...
Shared resources:
package sm.model;import org.apache.log4j.logger;public class threadfuncs {/** * Logger for this class */private static final Logger logger = logger.getlogger (Threadfuncs.class);p Rivate int sharenum;public threadfuncs (int Initsharenum) {this.sharenum = initsharenum;} PUBLIC&NBSP;VOID&NBSP;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&NBSP;==&NBSP;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 ();}}}
Thread 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 ();}}
Thread 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 ();}}
Test class:
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 ();}}}
Wait and notify in the "Java" thread