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.
Code:
PackageCom.qhong; Public classMain {/** 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 FinalMain t=NewMain (); 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 (); }}
Output:
1357924681011131517191214161820212325272922242628303133353739323436384041434547494244464850515355575952545658606163656769 62646668707173757779727476788081838587898284868890919395979992949698100
View Code
http://blog.csdn.net/junli_chen/article/details/49584187
Java multi-threading, threads alternate execution