Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to create threads in Java?

    • 0
    • 3
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 322
    Comment on it

    How to create threads in Java?

    From main thread we can create our own user defined threads, we can create threads in two ways:

    1. By extending thread class.
    2. By implementing run-able interface.

    By extending thread class

    Create a class which extends thread class. Thread class has two methods run() and start().

    In the subclass override run() i.e, write the task which we wanted to execute as a separate thread in run().

    In the main() method to start a thread create an object of subclass and call start().

    Example:

    public class Thread
    public static void main(String[] args)
    {
    System.out.println("main starts");
    MyThread1 t1 = new MyThread1();
    t1.start()
    for(int j=26;j<=50;j++)
    {
    System.out.println("j=" +j);
    try{
    Thread.sleep(500);
    }
    catch(Interrupted exception e)
    {
    e.PrintStackTrace();
    }
    }
    System.out.println("main ends");
    }
    }
    Class MyThreads extends thread
    {
    public void run()
    {
    System.out.println("My Thread1 starts");
    for(int i=1;i<=25;i++)
    {
    System.out.println("i ="+i);
    try{
    Thread.sleep(500);
    }
    catch(Interrupted exception e)
    {
    e.PrintStackTrace();
    }
    }
    System.out.println("My Thread1 ends")
    }
    

    By implementing run-able interface

    1. Create a class which implements run-able.
    2. Run-able has one abstract method run().
    3. In the subclass override run method and complete it i.e, write the code which you wanted to execute as a separate code.
    4. Create an object of type run-able and create an object of type thread by inputting run-able object.
    5. To start thread invoke start method of thread object.

    Example:

    public class Run
    {
    public static void main(String[] args)
    {
    Runable e1 = new Job1();
    Thread t1 = new Thread(r1);
    t1.start();
    }
    }
    class Job1 implements Runnable
    {
    public void run()
    {
    System.out.println("Thread1 Start");
    for(int i=1;i<=25;i++)
    {
    System.out.println("i ="+i);
    }
    }
    }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: