Use three threads to implement ABCABC ... Cycle.
The code is as follows:
//Tag class, which is used to share three threads, and is also a tag object with fast synchronization code in three threads. this tag I set to integer, but found that the integer addition operation will change the//Image reference (reason is auto-boxing), so an exception is thrown. So simply define the flag class yourself. class Flag{ intI=0; PublicSynchronizedvoidSetI () {i++;if(i==3) i=0; }}//Output a thread class Safetesta implements Runnable{ intnum=Ten; Flag Flag; PublicSafetesta (flag flag) { This. Flag=flag; } Public voidRun () {synchronized (flag) { while(true) {if(flag.i==0) {System.out.println ("A"); Flag.seti (); Flag.notifyall (); }Else{Try{flag.wait (); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); } } } } }/*public static void Main (string[] args) {Runnable sf=new safetest (); New Thread (SF). Start (); New Thread (SF). Start (); New Thread (SF). Start (); }*/}//Output B's thread: class safetestb implements Runnable{Flag Flag; PublicSAFETESTB (flag flag) { This. Flag=flag; } Public voidRun () { while(true) {synchronized (flag) { while(true) {if(flag.i==1) {System.out.println ("B"); Flag.seti (); Flag.notifyall (); }Else{Try{flag.wait (); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); } } } } } }}//Output C thread Public class SAFETESTC implements Runnable{Flag Flag; PublicSAFETESTC (flag flag) { This. Flag=flag; } Public voidRun () {synchronized (flag) { while(true) {if(flag.i==2) {System.out.println ("C"); Flag.seti (); Flag.notifyall (); }Else{Try{flag.wait (); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); } } } } } Public Static voidMain (string[] args) {Flag flag=NewFlag ();NewThread (NewSafetesta (flag)). Start ();NewThread (NewSAFETESTB (flag)). Start ();NewThread (NewSAFETESTC (flag)). Start (); }}
最关键的问题在于三个线程间的通信问题,是通过flag对象来标记的,之前出错是因为使用Integer来作为标记。这个例子也很好的给出了同步代码块的使用方法。我的这个代码有累赘的部分,三个线程类其实可以用一个来实现更简洁。
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java implementation Multithreading Classic problem: Using three threads to implement output ABCABC loops