Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa Java-Beginners Explain about threads:how to start program in threads?
Login         

View Questions and Answers by Category

Advertisements


 
Have Programming Question? Ask it here!
 
 
 


Harish Batchu
Explain about threads:how to start program in threads?
2 Answer(s)      3 years and a month ago
Posted in : Java Beginners


import java.util.*;
class AlphabetPrint  extends Thread
{
    public void print()
    {
        for(int i=1;i<=26;i++)
        {
            System.out.println((char)i);
        }
}
         public void run()
    {
        print();
    }
}

class NumberPrinter  extends Thread
{
    public void print()
    {
        for(int i=65;i<90;i++)
        {
            System.out.println(i);
        }
    }   
    public void run()
    {
        print();
    }
}

class AlphaNumericPrint
{
    public static void main(String[] args)
    {
        AlphabetPrinter ap = new AlphabetPrinter();
        ap.start();
        NumberPrinter np = new NumberPrinter();
        np.start();
    }
}

Advertisement
View Answers

December 13, 2011 at 3:50 PM




December 13, 2011 at 4:33 PM


Thread is a path of execution of a program. It can be called as single unit of execution in a program. A program can have more than one thread. Every program has at least one thread. Threads are used to do multiple activities simultaneously in a process. For example:- If you want to type something and show date and time simultaneously you can use threads. MS Word works on the principle of threads so that you can modify the file and print it simultaneously. Threads are called light weight processes.
Every java program has atleast one thread the main thread. When a java program starts, jvm creates the main thread and calls the program's main method. Additional thread is created by extending the Thread class.
Threads have three stages in its life. Start, run, stop. Threads can be started using start method, the start method automatically calls run method to make it running. To end the life cycle of the thread stop method is called or thread shows an exception or error or run method comes to an end.

In the above program 2 thread classes are created AlphabetPrint and NumberPrinter. The objects of the two classes is created in class AlphaNumericPrint and the two threads are started. When both are started the run() in each thread is automatically called and the lines in the corresponding run()s are executed. In the run method of NumberPrinter, print() is called which displays numbers from 65 to 89 and in the run() of AlphabetPrint calls print() of AlphabetPrint and displays the equivalent characters of integers 1 to 25.

Here the two processes displaying alphabets and numbers are done simultaneously.



Related Tutorials/Questions & Answers:
Advertisements
 

 

 

DMCA.com