PackageThreadTest; Public classTest1 {/** Two threads, one print 1-100 odd number, one print 1-100 even; requirements: Thread 1 prints 5, thread 2 begins printing, thread 2 prints 5, and thread 1 starts printing again to cycle. */ Private Static intState = 1; Private Static intNUM1 = 1; Private Static intnum2 = 2; Public Static voidMain (string[] args) {//TODO auto-generated Method Stub FinalTest1 T =NewTest1 (); NewThread (NewRunnable () {@Override Public voidrun () { while(num1<100){ //Two threads use the T object as a lock to ensure that only one thread is printed during each alternating period synchronized(t) {//if state!=1, stating that the thread 1 is not yet printed, thread 1 calls the Wait () method of T until the next time it wakes up if(state!=1){ Try{t.wait (); }Catch(interruptedexception e) {e.printstacktrace (); } } //when state=1, the turn thread 1 prints 5 times the number for(intj=0;j<5;j++) {System.out.println (NUM1); NUM1+=2; } //after thread 1 finishes printing, the state is assigned a value of 2, which means that the next turn to thread 2 printsState = 2; //The Notifyall () method wakes thread 2 on wait on T, and thread 1 exits the synchronization code block, releasing the T lockT.notifyall (); }}}). Start (); NewThread (NewRunnable () {@Override Public voidrun () { while(num2<100){ synchronized(t) {if(state!=2){ Try{t.wait (); }Catch(interruptedexception e) {e.printstacktrace (); } } for(inti=0;i<5;i++) {System.out.println (num2); Num2+=2; } State=1; T.notifyall (); } } } }). Start (); } }
Threads Run alternately