So far, we have used only two threads: the main thread and one child thread. However, your program can create more threads as needed. For example, the following program creates three child threads:
1 //Create multiple threads.2 classNewthreadImplementsRunnable {3String name;//Name of Thread4 Thread t;5 Newthread (String threadname) {6Name =ThreadName;7t =NewThread ( This, name);8System.out.println ("New Thread:" +t);9T.start ();//Start the threadTen } One A //The entry point for thread. - Public voidrun () { - Try { the for(inti = 5; i > 0; i--) { -SYSTEM.OUT.PRINTLN (name + ":" +i); -Thread.Sleep (1000); - } +}Catch(interruptedexception e) { -SYSTEM.OUT.PRINTLN (name + "interrupted")); + } ASYSTEM.OUT.PRINTLN (name + "exiting.")); at } - } - - classMultithreaddemo { - Public Static voidMain (String args[]) { - NewNewthread ("one");//Start Threads in NewNewthread ("the"); - NewNewthread ("three"); to Try { + //wait for other threads to end -Thread.Sleep (10000); the}Catch(interruptedexception e) { *System.out.println ("Main thread Interrupted"); $ }Panax NotoginsengSystem.out.println ("Main thread exiting.")); - } the}
The program output is as follows:
New Thread:thread[one,5,main]
New Thread:thread[two,5,main]
New Thread:thread[three,5,main]
One:5
Two:5
Three:5
One:4
Two:4
Three:4
One:3
Three:3
Two:3
One:2
Three:2
Two:2
One:1
Three:1
Two:1
One exiting.
The exiting.
Three exiting.
Main thread exiting.
As you can see, once started, all three sub-threads share the CPU. Note the call to sleep (10000) in main (). This causes the main thread to sleep for 10 seconds to make sure it ends.
Series Articles:
Java know how much (top)
Java know how much (interface) interface
Java knows how much (40) the difference between an interface and an abstract class
Java know how much (41) generic explanation
Java know how much (42) the range of generic wildcard characters and type parameters
Java know how much (43) Exception Handling Basics
Java know how much (44) exception type
Java know how much (45) uncaught exceptions
How much Java knows (the) use of try and catch
Java know how much (47) use of multiple catch statements
Java knows how much (in) the nesting of Try statements
Java know how much (a) throw: Exception throws
Java know how many () Java throws clauses
Java knows how many (or) finally
Java know how much (52) built-in exceptions
Java know how much (53) Use Java to create your own exception subclasses
Java know how much (54) assertion detailed
Java know how many (55) threads
Java know how much (56) threading ModelJava know how much (57) main threadJava know how much (58) thread Runnable interface and thread class explanation
Java know how much (59) Create multithreading