Login    New User    Forgot Password    Help      

Thread

Java Tutorials

thread is a program's path of execution. Most programs written today run as a single thread, causing problems when multiple events or actions need to occur at the same time. Let's say, for example, a program is not capable of drawing pictures while reading keystrokes. The program must give its full attention to the keyboard input lacking the ability to handle more than one event at a time. The ideal solution to this problem is the seamless execution of two or more sections of a program at the same time. Threads allows us to do this.

Multithreaded applications deliver their potent power by running many threads concurrently within a single program. From a logical point of view, multithreading means multiple lines of a single program can be executed at the same time, however, it is not the same as starting a program twice and saying that there are multiple lines of a program being executed at the same time. In this case, the operating system is treating the programs as two separate and distinct processes. Under Unix, forking a process creates a child process with a different address space for both code and data. However, fork() creates a lot of overhead for the operating system, making it a very CPU-intensive operation. By starting a thread instead, an efficient path of execution is created while still sharing the original data area from the parent.

Example

class tread1
{
public static void main(String args[])
{
Thread t= Thread.currentThread();
System.out.println("Current Thread "+t);

// renaming the thread
t.setName("Main Thread ");

 

int i;
try{
        for(i=1;i<=10;i++)
        {
        System.out.print(t);
        System.out.print("  ");
        Thread.sleep(1000);// sleep in milliseconds
        System.out.println(i);
        }
   }
   catch(InterruptedException e)
   {
    System.out.println("***");
   }

}
}

Output

Java Tutorials