Credits

Tuesday, May 3, 2011

Java's Thread Class

A thread is the execution of program from beginning to end. Multiple threads can be run to maximize computer resources. In a a multiple processor system, each processor can work on each tread simultaneously. However, in a single processor system, the threads are spliced or sliced in smaller parts and run concurrently over a period of time.

Every operating system like MS Windows  where threads are run may have different scheduling techniques (e.g first come, first serve, Round Robin, Higher Priority First, etc).

We can set priorities,  from 1 - 10, for our Java programs. Thus, when threads are of higher priority, they are performed first and threads lower priorities have to wait for higher - priority threads to end or to sleep. Threads of the priorities are performed in round - robin schedule.

The  programs below shall display the messages "Hi" and "Hello" but since a priority is assigned to each message, the "Hello" message is performed first, followed by the "Hi" message.  If threads are without priorities, the normal priority is acquired, thus, they are performed in round robin schedule.  So, in the other sample program, the messages "HI" and "HELLO" are displayed randomly.


[+/-] show/hide


/**
*
* @author Rose
*/
// a thread program where two threads are of normal priorities

class ThreadClass extends Thread{

String mymessage;

ThreadClass (String msg)
{ this.mymessage = msg;

}


@Override
public void run(){


for ( int x =1;x<=3;x++) System.out.println(this.mymessage); } } class ThreadSeatwork{ public static void main(String args[]){ ThreadClass greet1 = new ThreadClass("Hello"); ThreadClass greet2 = new ThreadClass("Hi"); greet1.start(); greet2.start(); } } /** * * @author Rose */ // a thread program using THread class where two treads have priorities class ThreadClass extends Thread{ String mymessage; ThreadClass (String msg, int priority) { this.mymessage = msg; setPriority(priority); } @Override public void run(){ for ( int x =1;x<=3;x++) System.out.println(this.mymessage); } } class ThreadSeatwork{ public static void main(String args[]){ ThreadClass greet1 = new ThreadClass("Hello",10); ThreadClass greet2 = new ThreadClass("Hi",1); greet1.start(); greet2.start(); } } /** * * @author Rose */ // a thread program using Runnable where two treads have priorities class ThreadClass implements Runnable{ Thread thread; String mymessage; ThreadClass (String msg, int priority) { thread = new Thread(this, msg); thread.setPriority(priority); thread.start(); } @Override public void run(){ mymessage = thread.getName(); for ( int x =1;x<=3;x++) System.out.println(mymessage); } } class ThreadSeatwork{ public static void main(String args[]){ new ThreadClass("Hello",10); new ThreadClass("Hi",1); } }

AddThis