Package Com.zs.thread;import Java.util.concurrent.TimeUnit; Public classSumthread { Public void One()throwsinterruptedexception{synchronized( This) {BooleanFlag =true; while(flag) { for(inti =1; I <= About; i + =2) {System. out.println(i);if(i== About) {flag =false; This.Notify(); Break; } This.Notify(); This.wait(); } } } } Public void Both()throwsinterruptedexception{synchronized( This) {BooleanFlag =true; while(flag) { for(inti =2; I <= -; i + =2) {System. out.println(i);if(i== -) {flag =false; This.Notify(); Break; } This.Notify(); This.wait(); } } } } Public Static void Main(string[] args)throwsException {Sumthread Sumthread =New Sumthread();NewThread (()->{Try{Sumthread. One(); }Catch(Exception e) {e.Printstacktrace(); } }).Start(); Timeunit.SECONDS.Sleep(1);NewThread (()->{Try{Sumthread. Both(); }Catch(Exception e) {e.Printstacktrace(); } }).Start(); }}
Two threads alternately print 1 to 100