Previous
Index

Next


Objective 2, When threads are prevented from executing

Recognise conditions that might prevent a thread from executing.

Comment on the objective

The expression "prevent a thread from executing" is slightly ambiguous, does it mean a thread that has been deliberately paused, or does it also include threads that have died?. A thread that is prevented from executing is said to be blocked.

Reasons a thread may be blocked

A thread may be blocked because

1) It has been put to sleep for a set amount of time

2) It is suspended with a call to suspend() and will be blocked until a resume() message

3) The thread is suspended by call to wait(), and will become runnable on a notify or notifyAll message.


For the purposes of the exam sleep(), and wait/notify are probably the most important of the situations where a thread can be blocked. 

The sleep method is static and pauses execution for a set number of milliseconds. There is a version that is supposed to pause for a set number of nanoseconds, though I find it hard to believe many people will work on a machine or Java implementation that will work to that level of accuracy. Here is an example of putting a Thread to sleep, note how the sleep method throws InterruptedException. The thread

public class TSleep extends Thread{
public static void main(String argv[]){
       TSleep t = new TSleep();
       t.start();
       }

       public void run(){
          try{
             while(true){
                  this.sleep(1000);
                  System.out.println("looping while");
                 }
            }catch(InterruptedException ie){}
       }
}


With the release of the Java2 platform the Thread methods stop, suspend and resume have been deprecated (no longer recommended for use, and will produce a warning at compile time). The JDK notes have the contain the following notice

//Quote

Deprecated. This method has been deprecated, as it is inherently deadlock-prone. If the target thread holds a lock on the monitor protecting a critical system resource when it is suspended, no thread can access this resource until the target thread is resumed. If the thread that would resume the target thread attempts to lock this monitor prior to calling resume, deadlock results. Such deadlocks typically manifest themselves as "frozen" processes. For more information see Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?.

//End Quote

Thread blocking via the wait/notify protocol is covered in the next topic 7.3

Using the Thread yield method.

Because of the platform dependent nature of Java threading you cannot be certain if a thread will ever give up its use of CPU resources to other threads. On some operating systems the threading algorithm may automatically give different threads a share of the CPU time, on others one thread might simply hog processor resources. For this reason the Java Thread class has a static method called yield which causes the currently running thread to yield its hold on CPU cycles. This thread returns to the "ready to run" state and the thread scheduling system has a chance to give other threads the attention of the CPU. If no other threads are in a "ready to run state" the thread that was executing may restart running again.

It is hard to demonstrate the benefits of using the yield method without being able to run some sample code on two different implementations on Java with different thread scheduling systems. Assuming that option is not available to you it is worth describing two main different scheduling systems used in operating systems.

Time slicing/preemptive

Each thread gets a set amount of CPU time for executing. Once it has used up its time with the CPU, it is removed from accessing the CPU and any other waiting Threads get a chance at CPU time. When each thread has had its chance with the CPU the cycle starts again.The beauty of this approach is that you can be confident that each thread will get at least some time executing.

Non time slicing/Cooperative

A priority system is used to decide which thread will run. A thread with the highest priority gets time with the CPU. A program under this system needs to be created in such a way that it "voluntarily" yield access to the CPU.

Java Thread Priorities

The Java Programmers exam does not expect you to understand or know about the system for setting Thread priorities. However it is worthwhile knowing about it, and its limitations so you can understand the importance of using the yield method of the Thread class. The priority of a thread can be set using the Thread.setPriority class and you can find out the priority by using the getPriority method. A newly created Thread gets set to Thread.NORM_PRIORITY.



Many years ago when Microsoft was a contender and IBM ruled the PC world there was extended debates over the merits of the pre-emptive scheduling system of OS/2 and the co-operative scheduling of Windows 3.x. With the co-operative system of Windows 3.x if one process (not quite the same as a Thread but the analogy holds) stopped responding it was very difficult to interrupt and kill that process. In theory, the preemptive system used with OS/2 meant that each process got a share of CPU time and if one process stopped responding it should still be possible to kill it.




Questions

Question 1)

What will happen when you attempt to compile and run this code?

public class TGo implements Runnable{
public static void main(String argv[]){
        TGo tg = new TGo();
        Thread t = new Thread(tg);
        t.start();
        }
        public void run(){
                while(true){
                        Thread.currentThread().sleep(1000);
                        System.out.println("looping while");
                        }
        }
}

1) Compilation and no output
2) Compilation and repeated output of "looping while"
3) Compilation and single output of "looping while"
4) Compile time error


Question 2)

Which of the following are recommended ways a Thread may be blocked?

1) sleep()
2) wait/notify
3) suspend
4) pause


Question 3)

Which of the following statements are true?

1) The sleep method takes parameters of the Thread and the number of seconds it should sleep
2) The sleep method takes a single parameter that indicates the number of seconds it should sleep
3) The sleep method takes a single parameter that indicates the number of milliseconds it should sleep
4) The sleep method is a static member of the Thread class

Question 4)

Which of the following statements are true?

1) A higher priority Thread will prevent a lower priorty Thread from getting any access to the CPU.

2) The yield method only allows any higher priority priority thread to execute.

3) The Thread class has a static method called yield

4) Calling yield with an integer parameter causes it to yield for a specific time.



Answers

Answer 1)

4) Compile time error
The sleep method throws InterruptedException and thus this code will not compile until the while loop is surrounded by a try/catch block


Answer 2)


1) sleep()
2) wait/notify

For the Java2 platform the suspend method has been deprecated and thus is valid but not recommended


Answer 3)

3) The sleep method takes a single parameter that indicates the number of milliseconds it should sleep
4) sleep is a static method of the Thread class

Answer 4

3) The Thread class has a static method called yield

A call to yield can allow any waiting thread to execute depending on the scheduling system of the underlying operating system. There is no version of yield that takes an integer parameter. Weather a higher priority thread gets CPU time than a lower priority thread is platform dependent and cannot be certain.




Other sources on this topic

This topic is covered in the Sun Tutorial at
http://java.sun.com/docs/books/tutorial/essential/threads/waitAndNotify.html

Commentry on deprecated Thread methods at
http://java.sun.com/docs/books/tutorial/post1.0/preview/threads.html

Jyothi Krishnan on this topic at
http://www.geocities.com/SiliconValley/Network/3693/obj_sec7.html#obj23








Previous
Index

Next