MainMenu

Home Java Overview Maven Tutorials

Thursday, 11 April 2019

MultiThreading in java

MultiThreading in java







Multitasking and Multithreading


1). Multitasking refers to a computer's ability to perform multiple jobs concurrently. For Example :- more than one program are running concurrently.
2).A Thread is a single sequence of execution within a program.
MultiThreading in java is a process of executing multiple threads simultaneously.
Multithreading refers to multiple threads of control with in a single program.
Each program can run multiple threads of control within it.

A Thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading both are used to acheive multitasking.
Threads use a shared memory area but processes are not.
A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of execution.
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses a shared memory area.
Java Multithreading is mostly used in games, animation etc.



For Example : Web browser is a program and its tabs are single thread.

Process :- An execution instance of a program is called a process. A thread is a subset of the process.


Advantage of Thread

1). To maintain responsiveness of an application during a long running task.
2).To enable cancellation of separable tasks.
3).Some problems are intrinsically parallel.
4).To monitor status of some resource (DB)
5). Some APIs and Systems demand it : Swing.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.

Application Thread

When we execute an application :-
The JVM creates a Thread object whose task is defined by the main() method.
It Starts the thread.
The thread executes the statements of the program one by one until the method returns and the thread dies.


Multiple Threads in an Application

Each thread has its private run-time stack
if two threads execute the same method, each will have its own copy of the local variables the methods uses.
However, all the threads see the same dynamic memory(heap)
Two different threads can act on the same object and same static fields concurrently.

Creating Thread

There are two ways to create our own Thread Object
1). By Extending Thread class OR Subclassing the Thread class and instantiating a new object of that class.
2). Implementing the Runnable interface.
In both the case the run() method should be implemented.

Life Cycle of a Thread

New Thread :- When a new thread is created, it is in new state. The thread has not yet started to run when thread is in this state.
Runnable State :- A thread that is ready to run is moved to runnable state. In this state, a thread might actually be running or int might be ready run at any instant of time. It is the responsibility of the thread scheduler to give the thread, time to run.
A multi-threaded program allocates a fixed amount of time to each individual thread.
Blocked/Waiting state: When a thread is temporarily inactive, then it’s in one of the following states:
Blocked
Waiting
For example, when a thread is waiting for I/O to complete, it lies in the blocked state. It’s the responsibility of the thread scheduler to reactivate and schedule a blocked/waiting thread. A thread in this state cannot continue its execution any further until it is moved to runnable state. Any thread in these states do not consume any CPU cycle.
A thread is in the blocked state when it tries to access a protected section of code that is currently locked by some other thread. When the protected section is unlocked, the schedule picks one of the thread which is blocked for that section and moves it to the runnable state.
Time waitingA thread lies in timed waiting state when it calls a method with a time out parameter. A thread lies in this state until the timeout is completed or until a notification is received.
Terminated State: A thread terminates because of either of the following reasons:
Because it exists normally. This happens when the code of thread has entirely executed by the program.
Because there occurred some unusual erroneous event, like segmentation fault or an unhandled exception.
A thread that lies in terminated state does no longer consumes any cycles of CPU.


------------------------------------------------------------------------------------------------------

Example of Thread :- extends Thread



import java.util.*;
class A extends Thread
{
public void run()
{
Scanner scn = new Scanner(System.in);
System.out.println("Enter your name");
String name = scn.nextLine();
System.out.println("Enter your surname");
String sname = scn.nextLine();
System.out.println("Your full Name is " + " " + name + " " + sname +" " + Thread.currentThread()) ;
}
}
public class ConsTest
{
public static void main(String args[])
{
A obj = new A();
obj.start();
}
}

Output :-
Enter your name
way2testing
Enter your surname
singh
Your full Name is way2testing singh Thread[Thread-0,5,main]

--------------------------------------------------------------------------------------------------------

Example of Thread :- implements Runnable



package com.lang.beginner; class A
{
public void test()
{
System.out.println("i am inside A class");
}
}
class B extends A implements Runnable
{
public void run()
{
Scanner scn = new Scanner(System.in);
System.out.println("Enter your name");
String name = scn.nextLine();
System.out.println("Enter your surname");
String sname = scn.nextLine();
System.out.println("Your full Name is " + " " + name + " " + sname +" " + Thread.currentThread()) ;
}
}
public class ConsTest
{
public static void main(String args[])
{
B obj = new B();
obj.test();
Thread th = new Thread(obj);
th.start();
}
}

Output :-
i am inside A class
Enter your name
way2testing
Enter your surname
.com
Your full Name is way2testing .com Thread[Thread-0,5,main]

---------------------------------------------------------------------------------------------------------

Example of Thread Synchronization


package com.lang.beginner;

import java.util.*;
class A implements Runnable
{
synchronized public void run()
{
Scanner scn = new Scanner(System.in);
System.out.println("Enter your name");
String name = scn.nextLine();
System.out.println("Enter your surname");
String sname = scn.nextLine();
System.out.println("Your full Name is " + " " + name + " " + sname +" " + Thread.currentThread()) ;
}
}
public class ConsTest
{
public static void main(String args[])
{
A obj = new A();
Thread th = new Thread(obj);
th.start();
A obj2 = new A();
Thread th2 = new Thread(obj);
th2.start();
}
}

Output :-
Enter your name
csc
Enter your surname
baji
Your full Name is csc baji Thread[Thread-0,5,main]
Enter your name
adhi
Enter your surname
raaj
Your full Name is adhi raaj Thread[Thread-1,5,main]

------------------------------------------------------------------------------------------------------------------

Example of Thread :-


package com.lang.Pages;
import org.testng.annotations.Test;

class parent
{
public void k()
{
System.out.println("i am inside parent class");
}
}
class test extends parent implements Runnable
{
public void run()
{
for(int i = 0; i<5; i++)
{
System.out.println("This is CSC" + " " + i);
}
}
public void run(int x)
{
for(int i = 0; i<x; i++)
{
System.out.println("This is run 2 CSC" + " " + i);
}
}
}
class test2 extends Thread
{
public void run()
{
for(int i = 0; i<5; i++)
{
System.out.println("This is way2testing" + " " + i);
}
}
}
public class ThreadPractice
{
@Test
public void k()
{
test obj = new test();
Thread td = new Thread(obj);
td.start();
test obj2 = new test();
obj2.run(7);
for(int i = 0; i<5; i++)
{
System.out.println("This is way2shayari" + " " + i);
}
test2 obj3 = new test2();
obj3.start();
}
@Test
public void l()
{
Thread t1 = new Thread(new Runnable()
{public void run()
{
for(int i = 0; i<5; i++)
{
System.out.println("i am thread 1 in same class");
}
}
}
);
Thread t2 = new Thread(new Runnable()
{public void run()
{
for(int i = 0; i<5; i++)
{
System.out.println("i am thread 2 in same class");
}
}
}
);
t1.start();
t2.start();
}
}
---------------------------------------------------------------------------------- Example of Threads

import java.util.Scanner;
class A implements Runnable
{
synchronized public void run()
{
for(int i = 1; i<11; i++)
{
System.out.println(i +" " +Thread.currentThread());
}
}
}
public class Oopstutorial
{
public static void main(String[] args)
{
A obj = new A();
Thread t1 = new Thread(obj);
Thread t2 = new Thread(obj);
t1.start();
t2.start();
}
}

Output :-
1 Thread[Thread-0,5,main]
2 Thread[Thread-0,5,main]
3 Thread[Thread-0,5,main]
4 Thread[Thread-0,5,main]
5 Thread[Thread-0,5,main]
6 Thread[Thread-0,5,main]
7 Thread[Thread-0,5,main]
8 Thread[Thread-0,5,main]
9 Thread[Thread-0,5,main]
10 Thread[Thread-0,5,main]
1 Thread[Thread-1,5,main]
2 Thread[Thread-1,5,main]
3 Thread[Thread-1,5,main]
4 Thread[Thread-1,5,main]
5 Thread[Thread-1,5,main]
6 Thread[Thread-1,5,main]
7 Thread[Thread-1,5,main]
8 Thread[Thread-1,5,main]
9 Thread[Thread-1,5,main]
10 Thread[Thread-1,5,main]

1 comment:

  1. This is definitely my go-to destination for satisfying my cool online shopping cravings. Get ready to discover some seriously cool stuffCool Online Shopping

    ReplyDelete