Introduction
In this blog, we will know about threading in java.
Thread: - A single flow of control in a program is
known as thread. This can execute independently in a processing environment and
perform an operation. A program can be divided into different parts or different
sequential flow of control known as a multithreaded program.
How to create a thread
A thread can be created by a java program by using
1.Java.lang.thread class
2.java.lang.Runnable interface
Creating of thread using thread class
1.create a class by inheriting thread class is required to provide a constructor to the class.
2.Override run () method to provide the logic for thread,
which can execute independently, run () method contains thread body.
3.Create an interface if the class which is created in step-1
4. To start the threads execution use start () method which
calls the run () method.
threadDemo.java file
- class mythread extends Thread {
- public void run() {
- for (int i = 0; i < 100; i++)
- System.out.println("Welcome to multithreading " + i);
- }
- }
- public class threadDemo {
- public static void main(String arg[]) {
- System.out.println("Main Started");
- mythread m = new mythread();
- m.start();
- System.out.println("main finished");
- }
- }
Compile
javac threadDemo.java
java threadDemo
Creating thread using runnable interface
1. Create a class, which must implement java.lang.Runnable
interface.
2.Override run () method to provide a body of the thread.
3. Create an instance of thread class which must accept an
instance of the class created in step-1 (subclass of runnable interface).
4. Start the execution of the thread call start method in the
Thread class instance.
thread_demo.java file
- import java.util.*;
- class mythread implements Runnable
- {
- public void run()
- {
- Scanner sc = new Scanner(System.in);
- System.out.println("Provide ur number");
- int x = sc.nextInt();
- System.out.println("No is " + x);
- }
- }
- public class thread_demo
- {
- public static void main(String arg[])
- {
- System.out.println("Main Started");
- mythread m1 = new mythread();
-
- Thread th = new Thread(m1);
- th.start();
- try
- {
-
-
-
- if (th.isAlive())
- th.join();
- } catch (Exception e) {}
- System.out.println("Main finished");
- }
- }
Compile
javac thread_demo.java
java thread_demo
Difference between multiprocessing and multithreading
Multiprocessing
1. A program in execution is known as process. Multiple
processes for a single environment are known as multiprocessing.
2. The minimum unit of multiprocessing is a program.
3. Process occupies its own resources or memory.
1. A part of a program, which can execute independently, is
known as Multithreading.
2. The minimum unit of Multithreading is thread or part of a
program.
3. Thread occupies the resources available to its process.
This also is called a lightweight process.