Interview questions:
The child thread loops 10 times, then the main thread loops 100 times, then goes back to the child thread loop 10 times, then the main thread loop 100 times, so loop 50 times, please write the program
/*** Sub-thread loop 10 times, then the main thread loop 100 times, then back to the child thread loop 10 times, and then the main thread loop 100 times, so loop 50 times, please write the program * *@authorAdministrator **/ Public classtraditionalthreadcommunication { Public Static voidMain (string[] args) {FinalBusiness Business =NewBusiness (); NewThread (NewRunnable () {@Override Public voidrun () { for(inti = 1; I <= 50; i++) {business.sub (i); }}). Start (); for(inti = 1; I <= 50; i++) {business.main (i); } }}classBusiness {Private BooleanIsshoudesub =true; /*** Synchronize with the resources you need to access the code, do not put on the thread *@paramI*/ Public synchronized voidSubinti) { while(!isshoudesub) {//It is also possible to use the IF, while to compare some as in the one argument version, interrupts and spurious wakeups is possible, and this method Should always being used in a loop Try{//prevents threads from being able to be woken up (while placed here to raise the level) This. Wait (); } Catch(interruptedexception e) {e.printstacktrace (); } } for(intj = 1; J <= 100; J + +) {System.out. println ("Sub thread sequence of" + j + ", loop of" +i); } isshoudesub=false; This. Notify (); } Public synchronized voidMaininti) { while(isshoudesub) {Try { This. Wait (); } Catch(interruptedexception e) {e.printstacktrace (); } } for(intj = 1; J <= 10; J + +) {System.out.println ("Main thread sequence of" + j + ", loop of" +i); } isshoudesub=true; This. Notify (); } /*** * Synchronized (obj) {Here obj must be the same as obj.wait, otherwise it throws an exception while (<condition does not hold>) Obj.wait (); ...//Perform action appropriate to condition}*/}
Several methods to use common data (including synchronous locks) or common algorithms should be grouped in the same class, which is a design that introduces high clustering and robustness of programs.
Java Multi-Threading and concurrent libraries advanced applications-traditional thread synchronous communication technology