Threads and Concurrent Programming

Threads may be seen as methods that execute at "the same time" as other methods. Normally, we think sequentially when writing a computer program. From this perspective, only one thing executes at a time. However, with today's multi-core processors, it is possible to literally have several things going on at the very same time while sharing the same memory. There are lots of ways that this is done in the real world, and this chapter goes over them in a way that you can apply to your own projects.

14.3 From the Java Library: java.

Thread Priority

The setPriority(int) method lets you set a thread’s priority to an integer value between Thread.MIN PRIORITY and Thread.MAX PRIORITY, the bounds defined as constants in the Thread class. Using setPriority() gives you some control over a thread’s execution. In general, higher-priority threads get to run before, and longer than, lowerpriority threads.

Annotation 2020-03-24 210653

To see how setPriority() works, suppose we change NumberThread’s constructor to the following:

Annotation 2020-03-24 210824

In this case, each thread sets its priority to its ID number. So, thread five will have priority five, a higher priority than all the other threads. Suppose we now run 2 million iterations of each of these threads. Because 2 million iterations will take a long time if we print the thread’s ID on each iteration, let’s modify the run() method, so that the ID is printed every 1 million iterations:

Annotation 2020-03-24 210925

Given this modification, we get the following output when we run Numbers:

Annotation 2020-03-24 211119

It appears from this output that the threads ran to completion in priority order. Thus, thread five completed 2 million iterations before thread four started to run, and so on. This shows that, on my system at least, the Java Virtual Machine (JVM) supports priority scheduling.

Annotation 2020-03-24 211216