Java Thread

Java Thread PDF Print E-mail
User Rating: / 2
PoorBest 
Contributed by Joe   
Thursday, 22 June 2006

Java thread overview

A thread is similar to the sequential programs described previously. A single thread also has a beginning, a sequence, and an end. At any given time during the runtime of the thread, there is a single point of execution. However, a thread itself is not a program; it cannot run on its own. Rather a thread runs within a program. The following figure shows this relationship.

The reason we need thread is that  many programs, of any size, contain some code segments that are more or less independent of one another, and that may execute more efficiently if the code segments could be overlapped in time. Threads provide a way to do this. Of course, if like most people your computer only has one processor, you can't execute more than one computation at any instant, but you can overlap input/output operations with processing.

Here are some thread examples:

E-mail programs don’t make you wait for all your messages to download
before you can read the first message. Instead, these programs use separate threads to display and download messages.

The Java Virtual Machine itself uses threading for some of its housekeeping chores. For example, the garbage collector runs as a separate thread so it can constantly monitor the state of the VM’s memory and decide when it needs to remove objects that are no longer being used to create some free memory.

How to Create java thread?

The Thread class has quite a few constructors,below is a list

Constructor
Explanation

Thread()

The basic Thread constructor without parameters. This constructor simply creates an instance of the Thread class.

Thread(String name)

Creates a Thread object and assigns the specified name to the thread.

Thread(Runnable target)

A more advanced constructor that lets you turn any object that implements an API interface called Runnable into a thread. You see how this constructor is used later in this chapter.

Thread(Runnable target, String name)

Creates a thread from any object that implements Runnable and assigns the specified name to the thread.

Thread(ThreadGroup group, String name)

Allocates a new Thread object.

 

A Summary of Methods Used with Threads

Class

Method

Type

Needs

Timeout Form

Thread

yield()

Static

 

no

Thread

sleep(#)

Static

try-catch

always

Thread

start()

Instance

 

no

Thread

run()

Instance

 

no

Thread

join()

Instance

try-catch

optional

Thread

interrupt ()

Instance

 

no

Object

wait()

Instance

synchronized, try-catch

optional

Object

notify()

Instance

synchronized

no

Object

notifyAll()

Instance

synchronized

no

To create a thread of control, you start by creating a SWrite object:

Thread worker = new Thread();

After a SWrite object is created, you can configure it and then run it. Configuring a thread involves setting its initial priority, name, and so on. When the thread is ready to run, you invoke its start method. 

Java Thread Example

public class ThreadDemo extends Thread
{
public void run()
{
for (int i = 10; i >= 0; i--)
{
System.out.println(“i= “ + i);
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{}
}
}
}

Creating and starting this thread. Here’s the main class

public class ThreadDemoApp
{
public static void main(String[] args)
{
Thread clock = new ThreadDemo();
clock.start();
}
}

 

Hot to Create two-threaded program?

Below is a simple two-threaded program that prints the words "ping" and "PONG" at different rates:

 


Questions 1 ( Java Threads tutorial for Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035))

You are creating a class that extends Object and implements Runnable. You have already written a run method for this class. You need a way to create a thread and have it execute the run method. Which of the following start methods should you use?

  • A.
  • public void start(){
        new Thread( this ).start();
     }
  • B.
  • public void start(){
       Thread myT = new Thread();
       myT.start();
    }
  • C.
  • public void start(){
       Thread myT = new Thread(this);
       myT.run();
    }

Answer A is correct. It correctly creates a new thread attached to the runnable object and starts it. It does not matter that there is no reference to the thread in the start method. Answer B is incorrect because the new thread is not attached to the runnable object, so it cannot find the run method. Instead, the default run in the Thread class is executed. Answer C is incorrect because the thread that is executing the start method calls run in the Thread class. The myT Thread is not started.


Questions 2 ( Java Threads tutorial for Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035))

You have created a TimeOut class as an extension of thread, the purpose of which is to print a "Time's Up" message if the thread is not interrupted within 10 seconds of being started.

Here is the run method that you have coded:

1. public void run(){
2.   System.out.println("Start!");
3.   try { Thread.sleep(10000 );
4.     System.out.println("Time's Up!");
5.   }catch(InterruptedException e){
6.     System.out.println("Interrupted!");
7.   }
8. }

Given that a program creates and starts a TimeOut object, which of the following statements is true?

  • A. Exactly 10 seconds after the start method is called, "Time's Up!" will be printed.
  • B. Exactly 10 seconds after "Start!" is printed, "Time's Up!" will be printed.
  • C. The delay between "Start!" being printed and "Time's Up!" will be 10 seconds plus or minus one tick of the system clock.
  • D. If "Time's Up!" is printed, you can be sure that at least 10 seconds have elapsed since "Start!" was printed.

Answer D is correct. It is the only statement that can be made with confidence. Answers A, B, and C are all incorrect because the expiration of a sleep timer does not guarantee that a thread will run—only that it can run.


Questions 3 ( Java Threads tutorial for Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035))

Thread Z holds the lock on object A. Thread X is blocked inside a wait call on ObjectA.
What allows thread X to become runnable?

  • A. Thread X is interrupted.
  • B. Thread X is interrupted.
  • C. Thread X’s wait() times out.
  • D. Thread Z calls Thread.sleep(100);
  • E. Thread Z releases the lock on A and calls the notify() method on thread X.
  • F. Thread Z releases the lock on A and calls the notifyAll() method on objectA.

Answer: F


Questions 4 ( Java Threads tutorial for Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035))

 You have written an application that can accept orders from multiple sources, each one of which runs in a separate thread. One object in the application is allowed to record orders in a file. This object uses the recordOrder method, which is synchronized to prevent conflict between threads.

While Thread A is executing recordOrder, Threads B, C, and D, in that order, attempt to execute the recordOrder method. What happens when Thread A exits the synchronized method?

  • A. Thread B, as the first waiting thread, is allowed to execute the method.
  • B. Thread D, as the last waiting thread, is allowed to execute the method.
  • C. Either A or D, but never C, will be allowed to execute.
  • D. One of the waiting threads will be allowed to execute the method, but you can't be sure which one it will be.

Answer D is correct. You cannot determine which thread will be allowed to execute next. Answers A, B, and C are incorrect because the JVM does not track the order in which threads attempt to access a locked object.


Questions 5 ( Java Threads tutorial for Sun Certified Programmer for Java 2 Platform 1.4 (CX-310-035)) 

What happens when thread X executes a wait() method on object A, without owning object A’s lock?

  • A. Compilation fails.
  • B. An exception is thrown.
  • C. The wait() method has no effect.
  • D. Thread X receives the lock immediately.
  • E. Object A moves the thread to the wait pool.

Answer: B

Last Updated ( Thursday, 27 July 2006 )

  home              contact us

 

©2006-2008 DeveloperZone.biz   All rights reserved     powered by Mambo Designed by Siteground