SlideShare une entreprise Scribd logo
1  sur  4
Programs on multithreading
yield()
package package2;
classMyThread extendsThread
{
publicvoidrun()
{
for(inti=1;i<=10;i++)
{
Thread.yield(); //thisthreadpausesandgivesachance to mainthreadto execute
System.out.println("child");
}
}
}
publicclassThreadDemo
{
publicstaticvoidmain(Stringargs[])
{
MyThread ob= newMyThread();
ob.start();
for(inti=1;i<=10;i++)
{
System.out.println("main");
}
}
}
Join()
package package2;
classMyThread2 extendsThread
{
publicvoidrun()
{
for(inti=1;i<=10;i++)
{
System.out.println("child2");
}
}
}
publicclassThreadDemo1{
publicstaticvoidmain(String[] args) throwsInterruptedException
{
// TODO Auto-generatedmethodstub
MyThread2 ob = newMyThread2();
ob.start();
for(inti=1;i<=10;i++)
{
ob.join(); //here mainthreadwaitsuntil childcontinues
System.out.println("main1");
}
}
}
Sleep()
package package2;
publicclass ThreadDemo6{
publicstaticvoidmain(String[] args) throws InterruptedException
{
// TODO Auto-generatedmethodstub
for(inti=0;i<=10;i++)
{
System.out.println("Slide -"+i);
Thread.sleep(5000);
}
}
}
package package2;
classMyThread3 extendsThread
{
publicvoidrun()ThreadPriorities
{
for(inti=1;i<=5;i++)
{
System.out.println("Name of thread="+Thread.currentThread().getName()+"number="+i);
}
}
}
classMyThread4 extendsThread
{
publicvoidrun()
{
for(inti=1;i<=5;i++)
{
System.out.println("Name of thread="+Thread.currentThread().getName()+"number="+i);
}
}
}
publicclassThreadPriorities
{
publicstaticvoidmain(String[] args)
{
// TODO Auto-generatedmethodstub
MyThread3 ob1 = newMyThread3();
ob1.setPriority(1);
ob1.start();
MyThread4 ob2 = newMyThread4();
ob2.setPriority(10);
ob2.start();
}
}
Synchronizationin Java
Synchronizationinjavaisthe capabilitytocontrol the accessof multiple threadstoanysharedresource.
Java Synchronizationisbetteroptionwhere we wanttoallow onlyone threadtoaccess the shared
resource.
The synchronizationismainlyusedto
 To preventthreadinterference.
 To preventconsistencyproblem.
There are twotypesof synchronization
 ProcessSynchronization
 ThreadSynchronization
Here,we will discussonlythreadsynchronization. Below isanexample of synchronizedmethoddisplay()
Example:
package package2;
classStu
{
publicsynchronizedvoiddisplay()
{
for(inti=0;i<10;i++)
System.out.println("Name of thread"+Thread.currentThread().getName());
}
}
classMyThread5 extendsThread
{
Stu ob;
MyThread5(Stuob)
{
this.ob=ob;
}
publicvoidrun()
{
ob.display();
}
}
publicclassThreadDemo4
{
publicstaticvoidmain(Stringargs[])
{
Stu ob= newStu();
MyThread5 t1 = newMyThread5(ob);
t1.start();
MyThread5 t2 = newMyThread5(ob);
t2.start();
MyThread5 t3 = newMyThread5(ob);
t3.start();
}
}
All the 3 threadsare accessingthe display() andsince we have made display() assynchronized.If one
threadis runningdisplay() method,all otherthreadswill wait.
yield(),Join(),Sleep(),InterruptedException,ThreadPriorities,Synchronizationin
Java,setPriority(),run(),currentThread().getName()

Contenu connexe

Similaire à Programs on multithreading

WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_03-Mar-2021_L13...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_03-Mar-2021_L13...WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_03-Mar-2021_L13...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_03-Mar-2021_L13...
MaruMengesha
 
C346_PA3_W12srccommonBaseThread.javaC346_PA3_W12srccommonB.docx
C346_PA3_W12srccommonBaseThread.javaC346_PA3_W12srccommonB.docxC346_PA3_W12srccommonBaseThread.javaC346_PA3_W12srccommonB.docx
C346_PA3_W12srccommonBaseThread.javaC346_PA3_W12srccommonB.docx
humphrieskalyn
 
Multithreaded programming
Multithreaded programmingMultithreaded programming
Multithreaded programming
Sonam Sharma
 
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfImplement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
kostikjaylonshaewe47
 
Java Programpublic class Fraction {   instance variablesin.pdf
Java Programpublic class Fraction {   instance variablesin.pdfJava Programpublic class Fraction {   instance variablesin.pdf
Java Programpublic class Fraction {   instance variablesin.pdf
aroramobiles1
 
とある断片の超動的言語
とある断片の超動的言語とある断片の超動的言語
とある断片の超動的言語
Kiyotaka Oku
 

Similaire à Programs on multithreading (20)

Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_03-Mar-2021_L13...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_03-Mar-2021_L13...WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_03-Mar-2021_L13...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_03-Mar-2021_L13...
 
Grid gain paper
Grid gain paperGrid gain paper
Grid gain paper
 
C++ Programming - 9th Study
C++ Programming - 9th StudyC++ Programming - 9th Study
C++ Programming - 9th Study
 
C346_PA3_W12srccommonBaseThread.javaC346_PA3_W12srccommonB.docx
C346_PA3_W12srccommonBaseThread.javaC346_PA3_W12srccommonB.docxC346_PA3_W12srccommonBaseThread.javaC346_PA3_W12srccommonB.docx
C346_PA3_W12srccommonBaseThread.javaC346_PA3_W12srccommonB.docx
 
Multithreaded programming
Multithreaded programmingMultithreaded programming
Multithreaded programming
 
Matching Game In Java
Matching Game In JavaMatching Game In Java
Matching Game In Java
 
Methods Of Thread Class
Methods Of Thread ClassMethods Of Thread Class
Methods Of Thread Class
 
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfImplement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
 
Operators
OperatorsOperators
Operators
 
Threads in java
Threads in javaThreads in java
Threads in java
 
Java Programpublic class Fraction {   instance variablesin.pdf
Java Programpublic class Fraction {   instance variablesin.pdfJava Programpublic class Fraction {   instance variablesin.pdf
Java Programpublic class Fraction {   instance variablesin.pdf
 
&Y tgs P kii for
&Y tgs P kii for&Y tgs P kii for
&Y tgs P kii for
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good Tests
 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptx
 
Ordering System IP2buildclasses.netbeans_automatic_buildO.docx
Ordering System IP2buildclasses.netbeans_automatic_buildO.docxOrdering System IP2buildclasses.netbeans_automatic_buildO.docx
Ordering System IP2buildclasses.netbeans_automatic_buildO.docx
 
とある断片の超動的言語
とある断片の超動的言語とある断片の超動的言語
とある断片の超動的言語
 
Play image
Play imagePlay image
Play image
 
Confitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsConfitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good Tests
 
Getting started with TDD - Confoo 2014
Getting started with TDD - Confoo 2014Getting started with TDD - Confoo 2014
Getting started with TDD - Confoo 2014
 

Plus de Lakshmi Sarvani Videla

Plus de Lakshmi Sarvani Videla (20)

Data Science Using Python
Data Science Using PythonData Science Using Python
Data Science Using Python
 
Menu Driven programs in Java
Menu Driven programs in JavaMenu Driven programs in Java
Menu Driven programs in Java
 
Recursion in C
Recursion in CRecursion in C
Recursion in C
 
Simple questions on structures concept
Simple questions on structures conceptSimple questions on structures concept
Simple questions on structures concept
 
Errors incompetitiveprogramming
Errors incompetitiveprogrammingErrors incompetitiveprogramming
Errors incompetitiveprogramming
 
Relational Operators in C
Relational Operators in CRelational Operators in C
Relational Operators in C
 
Recursive functions in C
Recursive functions in CRecursive functions in C
Recursive functions in C
 
Function Pointer in C
Function Pointer in CFunction Pointer in C
Function Pointer in C
 
Functions
FunctionsFunctions
Functions
 
Java sessionnotes
Java sessionnotesJava sessionnotes
Java sessionnotes
 
Singlelinked list
Singlelinked listSinglelinked list
Singlelinked list
 
Graphs
GraphsGraphs
Graphs
 
B trees
B treesB trees
B trees
 
Functions in python3
Functions in python3Functions in python3
Functions in python3
 
Dictionary
DictionaryDictionary
Dictionary
 
Sets
SetsSets
Sets
 
Lists
ListsLists
Lists
 
DataStructures notes
DataStructures notesDataStructures notes
DataStructures notes
 
Solutionsfor co2 C Programs for data structures
Solutionsfor co2 C Programs for data structuresSolutionsfor co2 C Programs for data structures
Solutionsfor co2 C Programs for data structures
 
C programs
C programsC programs
C programs
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Dernier (20)

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

Programs on multithreading

  • 1. Programs on multithreading yield() package package2; classMyThread extendsThread { publicvoidrun() { for(inti=1;i<=10;i++) { Thread.yield(); //thisthreadpausesandgivesachance to mainthreadto execute System.out.println("child"); } } } publicclassThreadDemo { publicstaticvoidmain(Stringargs[]) { MyThread ob= newMyThread(); ob.start(); for(inti=1;i<=10;i++) { System.out.println("main"); } } } Join() package package2; classMyThread2 extendsThread { publicvoidrun() { for(inti=1;i<=10;i++) { System.out.println("child2"); } } } publicclassThreadDemo1{ publicstaticvoidmain(String[] args) throwsInterruptedException { // TODO Auto-generatedmethodstub
  • 2. MyThread2 ob = newMyThread2(); ob.start(); for(inti=1;i<=10;i++) { ob.join(); //here mainthreadwaitsuntil childcontinues System.out.println("main1"); } } } Sleep() package package2; publicclass ThreadDemo6{ publicstaticvoidmain(String[] args) throws InterruptedException { // TODO Auto-generatedmethodstub for(inti=0;i<=10;i++) { System.out.println("Slide -"+i); Thread.sleep(5000); } } } package package2; classMyThread3 extendsThread { publicvoidrun()ThreadPriorities { for(inti=1;i<=5;i++) { System.out.println("Name of thread="+Thread.currentThread().getName()+"number="+i); } } } classMyThread4 extendsThread { publicvoidrun() { for(inti=1;i<=5;i++)
  • 3. { System.out.println("Name of thread="+Thread.currentThread().getName()+"number="+i); } } } publicclassThreadPriorities { publicstaticvoidmain(String[] args) { // TODO Auto-generatedmethodstub MyThread3 ob1 = newMyThread3(); ob1.setPriority(1); ob1.start(); MyThread4 ob2 = newMyThread4(); ob2.setPriority(10); ob2.start(); } } Synchronizationin Java Synchronizationinjavaisthe capabilitytocontrol the accessof multiple threadstoanysharedresource. Java Synchronizationisbetteroptionwhere we wanttoallow onlyone threadtoaccess the shared resource. The synchronizationismainlyusedto  To preventthreadinterference.  To preventconsistencyproblem. There are twotypesof synchronization  ProcessSynchronization  ThreadSynchronization Here,we will discussonlythreadsynchronization. Below isanexample of synchronizedmethoddisplay() Example: package package2; classStu { publicsynchronizedvoiddisplay() { for(inti=0;i<10;i++) System.out.println("Name of thread"+Thread.currentThread().getName()); } } classMyThread5 extendsThread { Stu ob; MyThread5(Stuob) { this.ob=ob; }
  • 4. publicvoidrun() { ob.display(); } } publicclassThreadDemo4 { publicstaticvoidmain(Stringargs[]) { Stu ob= newStu(); MyThread5 t1 = newMyThread5(ob); t1.start(); MyThread5 t2 = newMyThread5(ob); t2.start(); MyThread5 t3 = newMyThread5(ob); t3.start(); } } All the 3 threadsare accessingthe display() andsince we have made display() assynchronized.If one threadis runningdisplay() method,all otherthreadswill wait. yield(),Join(),Sleep(),InterruptedException,ThreadPriorities,Synchronizationin Java,setPriority(),run(),currentThread().getName()