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 in 1 ‘
New thread:                   Thread The 5.main)

One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3

One 2
Three:. 2
Two: 2
One: .1
Three: 1
” Two: 1
One exiting
Two exciting
Three exiting
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.

[vfb id=1]

Share This