Friday, May 25, 2012

1.7 Threads and Multithreading

The Thread Scheduler

The thread scheduler is the part of the JVM that decides which thread should run at any given moment, and also takes threads out of the run state. Assuming a single processor machine, only one thread can actually run at a time. Only one stack can ever be executing at one time. And it’s the thread scheduler that decides which thread among all other eligible threads will actually run. When I say eligible, it means threads that are in the runnable state.

Any thread in the runnable state can be chosen by the scheduler to be the one and only running thread. If a thread is not in a runnable state, then it cannot be chosen to be the currently running thread. And, to repeat something I have already said:


THE ORDER IN WHICH RUNNABLE THREADS ARE CHOSEN TO RUN IS NOT AND I MEAN IS NOT GUARANTEED!


Although we don’t control the thread scheduler, we can sometimes influence it. The following methods give us some tools for influencing the scheduler. Just don’t ever mistake influence for control.



Methods from the java.lang.thread Class

Some of the methods that can help us influence thread scheduling are as follows:
public static void sleep(long millis) throws InterruptedException
public static void yield()
public final void join() throws InterruptedException
public final void setPriority(int newPriority)

Note that both sleep() and join() have overloaded versions which not shown here.

Methods from the java.lang.object Class

Every class in Java inherits the following three thread-related methods:
public final void wait() throws InterruptedException
public final void notify()
public final void notifyAll()

The wait() method has three overloaded versions (including the one listed here).

Don't worry too much about the functionalities of these methods because we are going to have a full chapter dedicated to these babies.

For now, the chapter is over. You can give a sigh of relief which is exactly what I am doing now.. Huh!!!

No comments:

Post a Comment

java-8-streams-map-examples

package com.mkyong.java8; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; im...