Create a new thread with the following code:
1 Packagecom.thread.test;2 3 Public classMyThreadextendsThread {4 PrivateString name;5 PublicMyThread (String name) {6 This. Name =name;7 }8 @Override9 Public voidrun () {Ten for(inti = 0; I < 100; i++) { OneSystem.out.println (name+ "[" +i+ "]"); A } - Super. Run (); - } the}
After that, create a new test class with the following code:
1 Packagecom.thread.test;2 /*3 * 0-50 executes the main thread, 50-100 executes a thread, and the a thread executes completely before continuing the main thread4 */5 Public classthreaddemo{6 Public Static voidMain (string[] args) {7MyThread T =NewMyThread ("A");8 T.start ();9 for(inti = 0; I < 100; i++) {Ten if(i>50) { One Try { A T.join (); -}Catch(interruptedexception e) { - e.printstacktrace (); the } - } -System.out.println ("Main thread" + "[" +i+ "]"); - } + } -}
The following is an explanation of the join method in thread in the Java Platform SE8 API:
Public Final voidJoinLongMillis)throwsInterruptedexceptionwaits at the most millis milliseconds for ThisThread to die. A Timeout of 0means to wait forever. This implementation uses a loop of This. Wait calls conditioned on This. isAlive. As a thread terminates the This. Notifyall method is invoked. It is recommended this applications not use wait, notify, or Notifyall on Thread instances. Parameters:millis-The time to wait in milliseconds throws:illegalargumentexception-ifThe value of Millis is negative interruptedexception-ifAny thread have interrupted the current thread. The interrupted status of the current thread was cleared when ThisException is thrown.
Join methods in Java Multi-threading