Tuesday, June 17, 2008

Threads

Threads

A thread is a basic processing unit to which an operating system allocates processor time, and more than one thread can be executing code inside a process.

Every Java program has at least one thread, the thread that executes the Java program. It is created when you invoke the static main method of your Java class.

There are two ways to create a thread.

1. Extend the java.lang.Thread class
2. Implement the java.lang.Runnable interface.

1. Once you have a Thread object, you call its start method to start the thread.
2. When a thread is started, its run method is executed.
3. Once the run method returns or throws an exception, the thread dies and will be garbage-collected.

Every Thread has a state and a Thread can be in one of these six states.

1. new. A state in which a thread has not been started.
2. runnable. A state in which a thread is executing.
3. blocked. A state in which a thread is waiting for a lock to access an object.
4. waiting. A state in which a thread is waiting indefinitely for another thread to perform an action.
5. timed__waiting. A state in which a thread is waiting for up to a specified period of time for another thread to perform an action.
6. terminated. A state in which a thread has exited.

The values that represent these states are encapsulated in the java.lang.Thread.State enum. The members of this enum are NEW, RUNNABLE, BLOCKED, WAITING, TIMED__WAITING, and TERMINATED.

Change Thread Priority

1. A priority tells the operating system how much resource should be given to each thread.
2. A high-priority thread is scheduled to receive more time on the CPU than a low-priority thread. A method called Thread.setPriority() sets the priority of a thread. Thread class constants can be used to set these.

Stopping a Thread: Use boolean value to stop a thread
class CounterThread extends Thread {
public boolean stopped = false;

int count = 0;

public void run() {
while (!stopped) {
try {
sleep(1000);
} catch (InterruptedException e) {
}
System.out.println(count++);
;
}
}
}

public class MainClass {

public static void main(String[] args) {
CounterThread thread = new CounterThread();
thread.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
thread.stopped = true;
System.out.println("exit");
}

}

1. A daemon thread is a background thread.
2. It is subordinate to the thread that creates it.
3. When the thread that created the daemon thread ends, the daemon thread dies with it.

No comments:

Topics