1. To achieve the effect, direct:
1. The specific logic is clear, is through multithreading to achieve the direct code, lock control the same input or output thread synchronization,resource control the input and output thread synchronization
Class Resource{private String Name;private string sex;private boolean flag;public void SetName (String name) {this.name= Name;} public void Setsex (String sex) {this.sex=sex;} public void Setflag (Boolean flag) {This.flag=flag;} Public String GetName () {return this.name;} Public String Getsex () {return this.sex;} public Boolean Getflag () {return this.flag;}} Class Input implements Runnable{private static final object Lock=new object (); int num=0; Resource resource;public Input (Resource Resource) {This.resource=resource;} @Overridepublic void Run () {//TODO auto-generated method Stubwhile (! Thread.interrupted ()) {//Call interrupt method when terminating thread synchronized (lock) {synchronized (Resource) {if (Resource.getflag ()) {try {resource.wait ();} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} if ((num&1) ==0)//With an odd even number to achieve alternating output {resource.setsex ("male"); Resource.setname ("Mnmlist");} Else{resource.setsex ("female"); Resource.setname ("Sting");} Num++;if (num>10000) Thread.CurrentThread (). Interrupt (); Resource.setflag (true); Resource.notify ();}}}} Class Output implements Runnable{private static final object Lock=new object (); int num=0; Resource resource;public Output (Resource Resource) {This.resource=resource;} @Overridepublic void Run () {//TODO auto-generated method Stubwhile (! Thread.interrupted ()) {synchronized (lock) {synchronized (Resource) {if (!resource.getflag ()) {try {resource.wait ()}; catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} System.out.println (Thread.CurrentThread (). GetName () + "," + (++num) + "th, Name:" +resource.getname () + ", Gender:" + Resource.getsex ()), if (num>10000) Thread.CurrentThread (). interrupt (); Resource.setflag (false); Resource.notify ( );}}}}} public class Oneafteranotheroutput {public static void main (string[] args) {//TODO auto-generated method Stubresource Res Ource=new Resource (); input input=new input (Resource); output output=new output (Resource); input input1=new input ( Resource); Output output1=new output (Resource); Thread inputthread=nEW Thread (input); Thread outputthread=new thread (output); Thread inputthread1=new thread (INPUT1); Thread outputthread1=new thread (OUTPUT1); Inputthread.start (); Outputthread.start (); Inputthread1.start (); O Utputthread1.start ();}}
Alternating printing of communication problems between multiple threads