Showing posts with label Java Tutorial. Show all posts
Showing posts with label Java Tutorial. Show all posts
Multithreading in Java with example

Multithreading in Java with example

 

Multithreading in Java

Multithreading in Java

 When we want to run multiple programs or tasks simultaneously is known as multitasking. For example running VLC, Word, and Browser at a given time is an example of multitasking. Every program in memory is known as a process and each process has taken a single unit of time.

 The multitasking can be achieved by

  • Multiprocessing which is based on process and associated with operating system level.
  • Multitasking is based on thread and it is associated with programmer.

 
Multitasking

What is Thread in java?

A thread is a subpart of a process which lightweight and it is the smallest sequence of a program or a process. Each thread has some priority and the higher the priority higher the chances of executing preference.

The life cycle of thread

The JVM controlled the life cycle of a thread and it has five states 1. New, 2. Runnable, 3. Running, 4. Non-Runnable (Blocked) and last 5. Terminated.

How to create a thread in java?

We can thread in java by two method

First, With Thread class extending and second with implementing Runnable interface.

Java provides predefine API to implement thread, a few of commonly used API as follows

  • thread () Create a new thread
  • Thread (Runnable target)
  • Thread (String name)
  • Thread (Runnable target, String name)
  • Thread (ThreadGroup g, Runnable target)

To create a thread we used two way first by extending Thread class and second by implementing Runnable interface and this done by overriding the run() method. After then start() is called.


By implementing Runnable interface

public class RunnableInteface implements Runnable

{ 

    public void run()

    { 

        System.out.println("thread is running.. by Runnable interface"); 

    } 

    public static void main(String args[])

    { 

        RunnableInteface ob=new RunnableInteface(); 

        Thread t1 =new Thread(ob); 

        t1.start(); 

    } 

}

Output

thread is running.. by Runnable interface

In the above program, we implement a Runnable interface. And override the run() method and then create an object of the class and that object passed in the Thread class constructor as Thread(ob).


By extending class Thread

public class ExtendingThread extends Thread

{ 

    public void run()

    { 

        System.out.println("thread is running..by extending class Thread."); 

    } 

    public static void main(String args[])

    { 

        ExtendingThread t1=new ExtendingThread(); 

        t1.start(); 

    } 

} 

Output

thread is running..by extending class Thread.


Another example

public class DemoThread extends Thread

{

    public void run()

    {

        for(int i=0; i<5; i++)

        {

            System.out.println(getName() + "i=" + i);

        }

    }

    DemoThread() // constructor

    {

        start();

    }  

    public static void main(String args[])

    {

        DemoThread ob1 = new DemoThread();

        DemoThread ob2 = new DemoThread();

    }

}

In the above program run() method override and invoked by its constructor method, a loop is run from 0 to 4 and print the thread name with the help of getThread() method. In main() method two objects are created. It will print the following output

Thread-1 i=0

Thread-1 i=1

Thread-1 i=2

Thread-1 i=3

Thread-1 i=4

Thread-0 i=0

Thread-0 i=1

Thread-0 i=2

Thread-0 i=3

Thread-0 i=4


Difference between Daemon and User Threads


The main difference between Daemon and User threads is, a Daemon thread is low priority thread and User thread is a high priority thread.

Daemon thread is used in the background supporting task and User thread is used in the foreground.

Daemon thread life depends on the User thread whereas User Thread are independent.

 

Creating of Daemon Thread

public class Daemon extends Thread {

 

    @Override

    public void run()

    {

        System.out.println("User Thread or Non-Daemon Thread");

    }

}

class DaemonThread

{

    public static void main(String[] args)

    { 

        Daemon daemon = new Daemon();

        daemon.start(); 

        System.out.println("Main Thread"); 

        System.out.println("Is " + daemon.getName() + " a Daemon Thread: " + daemon.isDaemon()); 

        System.out.println("Is " + Thread.currentThread().getName() + " a Daemon Thread: "

        + Thread.currentThread().isDaemon());

    }

}

Inter-Thread communication

When a process communicates with synchronized threads is known as inter-thread communication. It is used to check thread pooling in java. This can be achieved by notify(), notifyAll() and wait() method.


Few points about the thread

  • A thread is the smallest unit of execution
  • Multiple tasks execution is multitasking from the user perspective and from multithreading from an operating system perspective
  • Thread is lightweight
  • Thread is a part of the process and it is an instance of a program
  • Java thread can be created either by class Thread or by interface Runnable
  • in a thread a run() method override
  • The start() method automatically invoke the run() method
  • The yield method of thread provides a chance to wait for another thread
  • join() method is used to wait till the thread finishes its execution
  • sleep() method is used to delay in execution
  • Suspending a thread can be resume again later on by resuming it
  • stop() method stop the thread and make it dead, it can not be resume again
  • synchronized can be used to synchronize the thread

More Java programs 


Program to find largest number among three numbers

Program to find largest number among three numbers

Program to find largest number among three numbers

Java program to display the big number where the user enters three numbers 

import java.util.*;

public class BigNumberPrint

{

    public static void main(String[] args)

    {

        int num1;                       // First Number

              int num2;                 // Second Number

        int num3;                       // Third Number

        int big;                // Store the largest number.

 

        // Scanner Object sc.

        Scanner sc = new Scanner(System.in);

 

        // Input the First number from the user.

        System.out.print("Enter first number: ");

        num1 = sc.nextInt();

              // Input the Second number from the user.

        System.out.print("Enter second number: ");

        num2 = sc.nextInt();

              // Input the Third number from the user.

        System.out.print("Enter third number: ");

        num3 = sc.nextInt();

 

        // Find the largest number among three number.

        if (num1 > num2 && num1 > num3)

        {

            big = num1;

        }

        else if (num2 > num3)

        {

            big = num2;

        }

        else

        {

            big = num3;

        }

 

        // Display a big number.

        System.out.println("Big number: " + big);

    }

} 

Output

Enter first number: 5

Enter second number: 8

Enter third number: 2

Largest number: 8

Program to find the largest number among three numbers

import java.util.*;

public class LargeNumberPrint

{

    public static void main(String[] args)

    {

        int num1;                       // Input First Number

        int num2;                       // Input Second Number

        int num3;                       // Input Third Number

        int large;                        // Store the largest number.

 

        // Scanner Object sc.

        Scanner sc = new Scanner(System.in);

 

        // Input the First number from the user.

        System.out.print("Enter first number: ");

        num1 = sc.nextInt();

        // Input Second number from the user.

        System.out.print("Enter second number: ");

        num2 = sc.nextInt();

        // Input Third number from the user.

        System.out.print("Enter third number: ");

        num3 = sc.nextInt();

        // Find the largest number among three numbers.

        if(num1 >= num2)

        { 

            if(num1 >= num3)

                large = num1;

            else

                large = num3; 

        }

        else

        {

            if(num2 >= num3)

                large = num2;

            else

                large = num3;

        }

        // Print the large number.

        System.out.println("Largest number: " + large);

    }

}

Output

Enter first number: 6

Enter second number: 9

Enter third number: 2

Largest number: 9

 More Java Program

Happy number in java

Celsius to Fahrenheit In Java – Fahrenheit To Celsius In Java

Magic number | Magic number in java

fibonacci Series in Java with recursive method

fibonacci Series in Java with recursive method

 

Fibonacci Series in Java with recursive method

Recursive method

When a function called by itself directly or indirectly is known as a recursive method or function. The function repeats itself several times and gives outputting the result and the end of each repetition.

Fibonacci Series in Java with recursive method

 A class RecursionFibonacciSeries has been defined to generate the Fibonacci series up to an nth number. Some of the members of the class are given below: 

  • Class Name : RecursionFibonacciSeries
  • Data Members/ instance variables: f1, f2, fib, number;
  • Constructor: RecursionFibonacciSeries ()
  • Member method: input(), fibo(int n), printFibseries()

 In the following java program, input is taken from the input() method.

Then it passes to as int fibo(int n) where the Fibonacci series generate recursively.

After it passes to printFibseries() method for printing of the series.

import java.util.*;

class RecursionFibonacciSeries

{

    // instance variables

    int f1,f2,fib,number;

    int i; // for iteration

    RecursionFibonacciSeries() //Constructor method

    {

        f1=0;

        f2=1;

        fib=0;

        number=0;

    }

    // enter nth value for the series

    void input()

    {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the number : ");

        number=sc.nextInt();

    }

    // Recursive method generating the 'nth' term of Fibonacci Series

    int fibo(int n)

    {

        if(n <= 1)

            return f1;

        else if(n == 2)

            return f2;

        else

            // recursion call

            return (fibo(n-1) + fibo(n-2));

    }

 

    void printFibseries() //Function generating all the Fibonacci Series numbers upto 'n' terms

    {

        System.out.println("The Fibonacci Series is:");

        for(i=1; i<=number; i++)

        {

            fib=fibo(i);

            // printing fibonacci series

            System.out.print(fib + "  ");

        }

    }

    // main method

    public static void main(String args[])

    {

        // object creation

        RecursionFibonacciSeries ob=new RecursionFibonacciSeries();

        // calling method

        ob.input(); 

        ob.printFibseries();

  } // end of main method

} // end of class

Output:

Enter the number : 15

The Fibonacci Series is:

0  1  1  2  3  5  8  13  21  34  55  89  144  233  377 

More Java programs