KEMBAR78
Threading Application | PDF | Thread (Computing) | Process (Computing)
0% found this document useful (0 votes)
12 views17 pages

Threading Application

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views17 pages

Threading Application

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

GIRI’S TECH HUB-PVT.

LTD-9175444433, 9049361265

Multithreading
________________________________________________________

Q. what is thread?
Thread is a sub part of process.

Q. what is process?
Process is a running program in ram called as process.

Q. what is multi threading?


To execute multiple thread simultaneously in waiting of each other.
Or to utilize idle period of processor called as multi threading.

Threading is a concept of operating system and java is language which provides implementation
to thread concept.

There are two ways to implement thread in java


1) Using Thread class
2) Using Runnable interface

How to create thread using a Thread class


___________________________________________________
Steps
1) Add java.lang package in application
import java.lang.*; this is the default package of java means we not need to import it.
2) Create class and inherit Thread class in it

class MyThread extends Thread


{
}
Here we create our own thread class name as MyThread and we inherit Thread class in it means
all properties of thread class present in MyThread class so we can say MyThread is thread

Note: Runnable is marker interface in java


Marker interfaces are the some interface that has special run time environment provided by
JVM

Visit: http://www.techhubindia.org Download APP – GIRI’S TECH HUB Page 1


GIRI’S TECH HUB-PVT.LTD-9175444433, 9049361265

3) Override run () method of Thread class


If we want to write thread logics we have run() method and run() is a method of Runnable
interface and Thread is implementer class of Runnable interface

Internal Structure
interface Runnable
{ public void run();
}
class Thread implements Runnable
{ public void run(){
}
}
class MyThread extends Thread {
public void run(){
//write here own logics
}
}

Example:
class MyThread extends Thread
{ public void run() {
for(int i=1; i<=5;i++) {
System.out.println("good morning\n");
}
}
}

4) Create object of thread class and use thread methods to work with thread.
___________________________________________________________________
Thread class provide multiple methods to us to work with thread

void start(): this method is used for start new thread or start thread and call run() method
internally. Means when we call start() method then JVM call run() method internally means we

Visit: http://www.techhubindia.org Download APP – GIRI’S TECH HUB Page 2


GIRI’S TECH HUB-PVT.LTD-9175444433, 9049361265

not need to call run() method manually and if we try to call run() manually using thread child
object then it not work as thread method.

public static void sleep(int seconds): this method is used for hold thread execution for a
specified time period.

public void stop(): this method is used for terminate thread or destroy thread.

public boolean isAlive(): this method check thread is running or not if running return true
otherwise return false.

public void join(): this method hold another thread execution when ever working thread not
complete its execution
etc

Object class methods for thread supporting work


void wait(),notify() and notifyAll()

Example:
package org.techhub;

class MyThread extends Thread {


public void run() {
try {
for (int i = 1; i <= 5; i++) {
System.out.println("First Thread "+i);
sleep(10000);
}
} catch (InterruptedException e) {
System.out.println(e);
}

}
}
class MyThread1 extends Thread

Visit: http://www.techhubindia.org Download APP – GIRI’S TECH HUB Page 3


GIRI’S TECH HUB-PVT.LTD-9175444433, 9049361265

{
public void run() {
try {
for (int i = 1; i <=50; i++) {
System.out.println("Second Thread "+i);
sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
public class MyThreadApplication {

public static void main(String[] args) {


MyThread m = new MyThread();
m.start();
MyThread1 m1 = new MyThread1();
m1.start();
}
}

Example:
package org.techhub;
class MyThread extends Thread {
public void run() {
try {
for (int i = 1; i <= 5; i++) {
System.out.println("First Thread "+i+"\t"+this.isAlive());
if(i==3) {
stop();
}
sleep(10000);
}
} catch (InterruptedException e) {

Visit: http://www.techhubindia.org Download APP – GIRI’S TECH HUB Page 4


GIRI’S TECH HUB-PVT.LTD-9175444433, 9049361265

System.out.println(e);
}

}
}
class MyThread1 extends Thread
{
public void run() {
try {
for (int i = 1; i <=50; i++) {
System.out.println("Second Thread "+i);
sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
public class MyThreadApplication {

public static void main(String[] args) throws InterruptedException{


MyThread m = new MyThread();
m.start();
m.join();
System.out.println("Now Thread status is "+m.isAlive());
MyThread1 m1 = new MyThread1();
m1.start();
}
}
Note: Every program contains by default thread called as main thread and it is start by JVM
internally.

Example:
package org.techhub;
public class MyThreadApplication {
public static void main(String[] args) throws InterruptedException{

Visit: http://www.techhubindia.org Download APP – GIRI’S TECH HUB Page 5


GIRI’S TECH HUB-PVT.LTD-9175444433, 9049361265

Thread t=Thread.currentThread();
String threadName=t.getName();
System.out.println("Thread Name is "+threadName);
}
}

Synchronization and Asynchronization


________________________________________________________________________
synchronization means if more than one thread use single resource sequentially one by one
called as synchronization and asynchronization means if two or more than two thread use
single resource simultaneously called as asynchronization

Q. what is resource?
here we can object is resource because in computer RAM consider as resource and object is
part of ram so here we can say resource means a object so we can say if two or more than two
threads using single object sequentially one by one called as synchronization and if two or more
than two thread use single object simultaneously called as asynchronization.

How to implement practically synchronization and asynchronization

Visit: http://www.techhubindia.org Download APP – GIRI’S TECH HUB Page 6


GIRI’S TECH HUB-PVT.LTD-9175444433, 9049361265

if we think about above diagram it represents asynchronization because we have only one
object name as Table and we share table reference in Two thread and in Three thread
so table reference or object use by two and three symultinioulsy called as asynchronzation

Source code of asynchronization


package org.techhub;
class Table{
void showTable(int no) {
try {
for(int i=1; i<=10; i++) {
System.out.printf("%d X %d = %d\n",i,no,i*no);
Thread.sleep(1000);
}
}
catch(Exception ex) {
System.out.println("Error is"+ex);
}
}
}
class Two extends Thread
{ Table table;
void setTable(Table table) {
this.table=table;
}
public void run() {
table.showTable(2);
}
}
class Three extends Thread{
Table table;
void setTable(Table table) {
this.table=table;
}
public void run() {
table.showTable(3);

Visit: http://www.techhubindia.org Download APP – GIRI’S TECH HUB Page 7


GIRI’S TECH HUB-PVT.LTD-9175444433, 9049361265

}
}
public class SyncAsyncApplication {
public static void main(String[] args) {
Table t1 = new Table();
Two tw = new Two();
tw.setTable(t1);
tw.start();
Three th = new Three();
th.setTable(t1);
th.start();
}
}
Source code of synchronization
package org.techhub;
class Table{
synchronized void showTable(int no) {
try {
for(int i=1; i<=10; i++) {
System.out.printf("%d X %d = %d\n",i,no,i*no);
Thread.sleep(1000);
}
}
catch(Exception ex) {
System.out.println("Error is"+ex);
}
}
}
class Two extends Thread
{ Table table;
void setTable(Table table) {
this.table=table;
}
public void run() {
table.showTable(2);
}

Visit: http://www.techhubindia.org Download APP – GIRI’S TECH HUB Page 8


GIRI’S TECH HUB-PVT.LTD-9175444433, 9049361265

}
class Three extends Thread{
Table table;
void setTable(Table table) {
this.table=table;
}
public void run() {
table.showTable(3);
}
}
public class SyncAsyncApplication {
public static void main(String[] args) {
Table t1 = new Table();
Two tw = new Two();
tw.setTable(t1);
tw.start();
Three th = new Three();
th.setTable(t1);
th.start();
}
}

Now we want to discuss about wait(),notify() and notifyAll()


______________________________________________________________________

void wait(): this method is used for hold thread execution for a specified time period it is a
method of Object class.
There are two types of wait
i) Conditional wait : conditional wait means when thread re-execute if self after some specified
time period called as conditional wait.

Syntax: void wait(int milliseconds)

ii) Unconditional wait: unconditional wait means when thread not re-execute itself and we
need to send request to thread for re-execution called as unconditional wait and for that we
have notify() and notifyAll()

Visit: http://www.techhubindia.org Download APP – GIRI’S TECH HUB Page 9


GIRI’S TECH HUB-PVT.LTD-9175444433, 9049361265

Syntax void wait();

Note: notify() and notifyAll() method help us to re-execute thread when they are in
unconditional wait.

notify(): this method is used for call waited thread in first in first out format and call only one
thread at time.

notifyAll(): this method is used for call all waited thread in last in first out format means we can
say notifyAll() method implement stack.

Example:
package org.techhub;
class Table{
synchronized void showTable(int no) {
try {
for(int i=1; i<=10; i++) {
System.out.printf("%d X %d = %d\n",i,no,i*no);
if(i==5) {
wait();
}
Thread.sleep(1000);
}
}
catch(Exception ex) {
System.out.println("Error is"+ex);
}
}
public synchronized void recall() {
try {
notifyAll();
}
catch(Exception ex){

}
}

Visit: http://www.techhubindia.org Download APP – GIRI’S TECH HUB Page 10


GIRI’S TECH HUB-PVT.LTD-9175444433, 9049361265

}
class Two extends Thread
{ Table table;
void setTable(Table table) {
this.table=table;
}
public void run() {
table.showTable(2);
}
}
class Three extends Thread{
Table table;
void setTable(Table table) {
this.table=table;
}
public void run() {
table.showTable(3);
}
}
public class SAAPP {
public static void main(String[] args) {
Table t1 = new Table();
Two tw = new Two();
tw.setTable(t1);
tw.start();
Three th = new Three();
th.setTable(t1);
th.start();

do {
java.util.Scanner xyz = new java.util.Scanner(System.in);
String msg=xyz.nextLine();
if(msg.equals("restart")) {
t1.recall();
}
if(msg.equals("stop")) {

Visit: http://www.techhubindia.org Download APP – GIRI’S TECH HUB Page 11


GIRI’S TECH HUB-PVT.LTD-9175444433, 9049361265

System.exit(0);
}

}while(true);
}
}

Q. what is diff between wait() and sleep() method?


_____________________________________________________________________
Wait Sleep
wait() is a method of java.lang.Object class sleep() is a static method of Thread class
wait() method only works in synchronized sleep() can work in synchronized as well as
block asynchronized block.
wait() can work with conditional as well as Sleep() can only with a conditional state
unconditional state

Q. what is diff between notify() and notifyAll()?


notify() can fetch single waited thread at a time and notifyAll() can fetch all waited thread a
time and notify() use queue algoritham and notifyAll() use stack logics

How to implement thread By using a Runnable interface


_____________________________________________________________________

Q. Why we need to implement thread using a Runnable interface?


Sometime in the case of Multi threading there is possibility of multiple inheritance
and if we want to implement thread in this scenario then we need to use Runnable interface for
implement thread.

abstract class B{
}
class A extends B,Thread
{
}

Visit: http://www.techhubindia.org Download APP – GIRI’S TECH HUB Page 12


GIRI’S TECH HUB-PVT.LTD-9175444433, 9049361265

Note: if we think about above code we have class A which has two parent class name as B and
Thread so this type of inheritance generate situation for multiple inheritance but as per the
norms of java we cannot handle multiple inheritance situation using classes so if we want to
use thread in this situation java suggest use Runnable interface for implement thread.

Steps to work with Runnable interface in java?


1) add the java.lang package in application
import java.lang.*;
2) Create user defined class and implement Runnable interface in it
class Test implements Runnable
{
}
3) override its run() and write logics
class Test implements Runnable
{
@Override
public void run() {
try {
for(int i=1;i<=5; i++) {
System.out.println("I = "+i);
Thread.sleep(10000);
}
}
catch(Exception ex) {
System.out.println("Error is "+ex);
}
}
}
4) create object of Runnable implementer class
Test t = new Test();
5) Use Thread class constructor to create object of thread
________________________________________________________________
when we use Runnable interface for implement thread then we have thread class constructor

Thread ref = new Thread(Runnable): here we can pass reference of Runnable implement class
object as parameter in thread class constructor and create object of thread.

Visit: http://www.techhubindia.org Download APP – GIRI’S TECH HUB Page 13


GIRI’S TECH HUB-PVT.LTD-9175444433, 9049361265

6) Use Thread class methods for work with thread


package org.techhub;
class Test implements Runnable
{
@Override
public void run() {
try {
for(int i=1;i<=5; i++) {
System.out.println("I = "+i);
Thread.sleep(1000);
}
}
catch(Exception ex) {
System.out.println("Error is "+ex);
}
}
}
public class ThreadRunnableApp {
public static void main(String[] args) {
Test t1 = new Test();
Thread th = new Thread(t1);
th.start();
}
}

threading topics – (hold)


thread priority
daemon thread
thread pool
volatile keywords

Visit: http://www.techhubindia.org Download APP – GIRI’S TECH HUB Page 14


GIRI’S TECH HUB-PVT.LTD-9175444433, 9049361265

Visit: http://www.techhubindia.org Download APP – GIRI’S TECH HUB Page 15


GIRI’S TECH HUB-PVT.LTD-9175444433, 9049361265

Visit: http://www.techhubindia.org Download APP – GIRI’S TECH HUB Page 16


GIRI’S TECH HUB-PVT.LTD-9175444433, 9049361265

Visit: http://www.techhubindia.org Download APP – GIRI’S TECH HUB Page 17

You might also like