Saturday, May 28, 2011

Java program using Thread and its methods.



A simple Java program for creating threads by using threads concept along with it’s methods. As Java applications and applets are naturally threaded. The runtime environment starts execution of the program with the main() method in one thread. Garbage collection takes place in another thread. Screen updating occurs in a third thread. There may be other threads running as well, mostly related to the behavior of the virtual machine. All of this happens invisibly to the programmer. The simplest reason for adding a separate thread is to perform a long calculation. Any operation that is going to take a noticeable period of time should be placed in its own thread.
The other reason to use threading is to more evenly divide the computer's
power among different tasks. With threads you can set the priority of different processes.



Using Multithreading:

Java is inherently multi-threaded. A single Java program can have many different threads executing independently and continuously. Three Java applets on the same page can run together with each getting equal time from the CPU with very little extra effort on the part of the programmer.

This makes Java very responsive to user input. It also helps to contribute to Java's robustness and provides a mechanism whereby the Java environment can ensure that a malicious applet doesn't steal all of the host's CPU cycles.

Program:
class first extends Thread
{
public void run()
{
for( int i=1;i<=10;i++)
{
System.out.println("First thread i=  "+i);
if(i==3)
yield();
}
System.out.println("End of first thread");
}
}
class second extends Thread
{
public void run()
{
try
{
for( int j=1;j<=10;j++)
{
System.out.println("second thread j=  "+j);
if(j==4)
sleep(1000);
}
}
catch(Exception e)
{
System.out.println("error");
}
System.out.println("End of second thread");
}
}
class third extends Thread
{
public void run()
{
for( int k=1;k<=10;k++)
{
System.out.println("Third thread k=  "+k);
if(k==5)
{
System.out.println("End of third thread");
stop();
}
}
}
}


class ThreadDemo
{
public static void main(String [ ]args)
{
first f=new first();
second s=new second();
third t=new third();
f.start();
s.start();
t.start();
}
}



No comments:

Post a Comment