Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Multithreading in Java

    • 0
    • 4
    • 1
    • 4
    • 0
    • 0
    • 0
    • 0
    • 396
    Comment on it

    Multithreading is the process of running two or more threads executing altogether within a single program in Java. Before understanding this let me first explain what threads exactly are.

    A thread is a light-weight process that runs independently in a program. There can be as many threads in a program. A thread can have stages in its life. Threads share a common memory area thus, take less time in context-switching and hence increases the execution speed. Threads are majorly used in the gaming and animation industry.

    java.lang.Thread class is the main class that controls all the threads and hence a thread always extend this class.

    Stages of a Thread:

    New: when a program starts, the thread is in new stage,

    Runnable: after a thread is started, it is in runnable stage and is executing its tasks,

    Waiting: when a thread is waiting for the other thread to response and go to the runnable stage when it is being responded by the other thread to continue,

    Time waiting: when a thread is waiting for an event to occur or when it is running for an interval and the interval expires,

    Terminated: when it completes the execution of its tasks or is terminated.

    A simple example:

    MainThreadClass.java 
    
    public class MainThreadClass {
    
        public static void main(String[] args) {
    
            ThreadClass mt1=new ThreadClass("Run");
            ThreadClass mt2=new ThreadClass("Thread");
    
            mt1.start(); // this will start thread of object 1
            mt2.start(); // this will start thread of object 2
        }
    }
    
    public class MyThreadClass extends Thread{
        String msg;
        public void run()
        {
            for(int i=0;i<=5;i++)
            {
                System.out.println("Sample: "+msg);
            }
        }
    
        MyThreadClass(String mg)
        {
            msg=mg;
        }
    }
    

    Output:

    Sample: Run Sample: Run Sample: Run Sample: Thread Sample: Run Sample: Run Sample: Thread Sample: Thread Sample: Thread Sample: Thread Sample: Run Sample: Thread

 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: