Creating Multiple Threads
So far, you have been using only two threads the main thread and. one child thread. However, your program can spawn as many threads as it needs. For example, the following program creates three child threads:
The output from-this program is shown here:
New thread: Thread O~/5,.rnain]
New thread: Thread Two I 5.mil in 1 ‘
New thread: Thread The 5.main)
” Two: 1
Main’ thread exiting.
As you can see, once started, all three child threads share the CPU. Notice the call to sleep(lOOOO)in maine ). This causes the main thread to sleep for ten seconds and ensures ensures that it will finish last.