classdo8{ Public Static voidMain (string[] args) {Resource R=NewResource (); Input in=NewInput (R); Output out=NewOutput (R); Thread T1=NewThread (in); Thread T2=NewThread (out); T1.start (); T2.start (); }}classresource{String name; String sex; Booleanflag=false;}//inputclassInputImplementsrunnable{Resource R; Input (Resource r) { This. r=S; } Public voidrun () {intX=0; while(true) { synchronized(r) {if(r.flag) {Try{r.wait ();}Catch(Exception e) {}//when True, the current line layer stops } if(x==0) {R.name= "Go Inside"; R.sex= "Male"; } Else{r.name= "Xiaoli"; R.sex= "Wumen"; } R.flag=true; R.notify ();//start any of the stopped line layers} x= (x+1)%2; } }}//OutputclassOutputImplementsrunnable{Resource R; Output (Resource r) { This. r=R; } Public voidrun () { while(true) { synchronized(r) {if(!r.flag) {Try{r.wait ();}Catch(Exception e) {}//when not true, the current line layer stops } Try{thread.sleep (100);}Catch(Exception e) {} System.out.println (R.name+"..."+r.sex); R.flag=false; R.notify ();//start any of the stopped line layers } } }}
Start and stop of Java line layer