Java Programming

Topic No. 9 : About Multithreading

About Thread and Multithreading

A thread is a flow of execution through the process code.Multithreading is a feature of Java language which allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.

Threads can be created by using two mechanisms :

Extending the Thread class
Implementing the Runnable Interface

Example : By extending Thread Class
Source Code of main class
package javaapplication1;

public class JavaApplication1 {
   
    public static void main(String[] args) {
        t1 t = new t1();
        t.start();
        t2 tt = new t2();
        tt.start();
        t3 ttt = new t3();
        ttt.start();
           
    }
}           
Source Code of t1 class
public class t1 extends Thread {
    public void run()
    {
        for(int i=1;i<101;i++)
        {
        System.out.print("\n " +i);
        }
    }
}
Source Code of t2 class
public class t2 extends Thread {
    public void run()
    {
        for(int i=101;i<201;i++)
        {
        System.out.print("\n " +i);
        }
    }
}
Source Code of t3 class
public class t3 extends Thread {
    public void run()
    {
        for(int i=201;i<301;i++)
        {
        System.out.print("\n " +i);
        }
    }
}
Example : By implementing Runnable Interface
Source Code of main class
package javaapplication1;

public class JavaApplication1 {
   
    public static void main(String[] args) {
        t11 t = new t11();
        Thread th = new Thread(t);
        th.start();
        t2 tt = new t2();
        tt.start();
        try
        {
        Thread.sleep(5000);
        }
        catch(Exception e)
        {
        System.out.print(e.toString());
        }
        t3 ttt = new t3();
        ttt.start();
           
    }
}           
Source Code of t1 class
public class t11 implements Runnable {
    public void run()
    {
        for(int i=1;i<101;i++)
        {
        System.out.print("\n"+i);
        }
    }
}
Source Code of t2 class
public class t2 extends Thread {
    public void run()
    {
        for(int i=101;i<201;i++)
        {
        System.out.print("\n " +i);
        }
    }
}
Source Code of t3 class
public class t3 extends Thread {
    public void run()
    {
        for(int i=201;i<301;i++)
        {
        System.out.print("\n " +i);
        }
    }
}