SlideShare une entreprise Scribd logo
1  sur  36
Multi-threading U Nyein Oo COO/Director(IT) Myanma Computer Co., Ltd IADCS Diploma Course
What’s a Thread? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],1. Introduction
Initial Remarks about Threads ,[object Object],[object Object],[object Object],[object Object],[object Object],1. Introduction (cont;)
Some spesific uses for threads ,[object Object],[object Object],[object Object],[object Object],[object Object],1. Introduction (cont;)
Multitasking vs. Multithreading ,[object Object],[object Object],[object Object],[object Object],1. Introduction (cont;)
Overview of Multitasking ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],1. Introduction (cont;)
Processes in a Multitasking Environment ,[object Object],1. Introduction (cont;)
Overview of Multithreading ,[object Object],[object Object],1. Introduction (cont;)
Properties of Multiple Threads ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],1. Introduction (cont;)
Possible Uses for Multithreading ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],1. Introduction (cont;)
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
3. Threaded States: Life Cycle of a Thread ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
3. Thread States: Life Cycle of a Thread
4. Thread Priorities and Thread Scheduling ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
ThreadTester.java //ThreadTester.java public class  ThreadTester { // create and start threads public static void  main( String args[] ) { PrintThread thread1, thread2, thread3, thread4; // create four PrintThread objects thread1 =  new  PrintThread(  "thread1"  ); thread2 =  new  PrintThread(  "thread2"  ); thread3 =  new  PrintThread(  "thread3"  ); thread4 =  new  PrintThread(  "thread4"  ); System.err.println(  "Starting threads"  ); // start executing PrintThreads thread1.start(); thread2.start(); thread3.start(); thread4.start(); System.err.println(  "Threads started"  ); } }  // end class ThreadTester Class  ThreadTester  creates four  PrintThread s and calls their  start  methods
ThreadTester.java Lines 33-71 Lines 38-48 Lines 51-69 class  PrintThread  extends  Thread { private int  sleepTime; // PrintThread constructor assigns name to thread  // by calling superclass Thread constructor public  PrintThread( String name ) { super ( name ); // sleep between 0 and 5 seconds sleepTime = ( int ) ( Math.random() *  5000  ); // display name and sleepTime System.err.println(  "Name: "  + getName() +  ";  sleep: "  + sleepTime ); } // control thread's execution public void  run() { // put thread to sleep for a random interval try  { System.err.println( getName() +  " going to sleep"  ); // put thread to sleep Thread.sleep( sleepTime ); } Thread  run  method prints a  String  saying the thread is going to sleep and thread sleeps // if thread interrupted during sleep, catch exception  // and display error message catch  ( InterruptedException interruptedException ) { System.err.println( interruptedException.toString() ); } // print thread name System.err.println( getName() +  " done sleeping"  ); } }  // end class PrintThread Thread prints name when done sleeping PrintThread  inherits from  Thread  so each object of the class can execute in parallel Constructor initializes  sleepTime  to be 0 to 4.999 seconds and outputs name and value of  sleepTime
5. Thread Synchronization ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
6. Producer/Consumer Relationship without    Synchronization ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
ProduceInteger.java Line 10 Lines 15-37 //ProduceInteger.java public class  ProduceInteger  extends  Thread { private  HoldIntegerUnsynchronized sharedObject; // initialize ProduceInteger thread object public  ProduceInteger( HoldIntegerUnsynchronized shared ) { super (  &quot;ProduceInteger&quot;  ); sharedObject = shared; } // ProduceInteger thread loops 10 times and calls  // sharedObject's setSharedInt method each time public void  run() { for  (  int  count =  1 ; count <=  10 ; count++ ) { // sleep for a random interval try  { Thread.sleep( (  int  ) ( Math.random() *  3000  ) ); } // process InterruptedException during sleep catch ( InterruptedException exception ) { System.err.println( exception.toString() ); } // call sharedObject method from this  // thread of execution sharedObject.setSharedInt( count ); } Method  run  loops 10 times,  sleep ing 0-3 seconds and calling  setSharedInt System.err.println(  getName() +  &quot; finished producing values&quot;  + &quot;Terminating &quot;  + getName() ); } }  // end class ProduceInteger Thread prints that it finished Instance variable  sharedObject  refers to object  shared
ConsumeInteger.java Line 10 Lines 15-39 Line 23 Lines 31-32 //ConsumeInteger.java public class  ConsumeInteger  extends  Thread { private  HoldIntegerUnsynchronized sharedObject; // initialize ConsumerInteger thread object public  ConsumeInteger( HoldIntegerUnsynchronized shared ) { super (  &quot;ConsumeInteger&quot;  ); sharedObject = shared; } // ConsumeInteger thread loops until it receives 10 // from sharedObject's getSharedInt method public void  run() { int  value, sum =  0 ; do  { // sleep for a random interval try  { Thread.sleep( ( int ) ( Math.random() *  3000  ) ); } // process InterruptedException during sleep catch ( InterruptedException exception ) { System.err.println( exception.toString() ); } value = sharedObject.getSharedInt(); sum += value; }  while  ( value !=  10  ); Each iteration causes the thread to  sleep  0-3 seconds Call method  getSharedInt  and assign to variable  sum System.err.println( getName() +  &quot; retrieved values totaling: &quot;  + sum + &quot;Terminating &quot;  + getName() ); } }  // end class ConsumeInteger Thread prints that it is done consuming Initializes  sharedObject  to refer to object  shared Method  run  contains a  do / while  structure that loops 10 times
HoldIntegerUnsynchronized.java Line 4 Lines 7-13 Lines 16-22 // HoldIntegerUnsynchronized.java // Definition of class HoldIntegerUnsynchronized. public class  HoldIntegerUnsynchronized { private int  sharedInt =  -1 ; // unsynchronized method to place value in sharedInt public void  setSharedInt(  int  value ) { System.err.println( Thread.currentThread().getName() + &quot; setting sharedInt to &quot;  + value ); sharedInt = value; } // unsynchronized method return sharedInt's value public int  getSharedInt() { System.err.println( Thread.currentThread().getName() + &quot; retrieving sharedInt value &quot;  + sharedInt ); return  sharedInt; } }  // end class HoldIntegerUnsynchronized Instance variable  sharedInt  is the shared buffer Method  setSharedInt  not  synchronized Method  getSharedInt  not  synchronized
SharedCell.java Lines 6-20 //SharedCell.java // Show multiple threads modifying shared object. public class  SharedCell { // execute application public static void  main( String args[] ) { HoldIntegerUnsynchronized sharedObject = new  HoldIntegerUnsynchronized(); // create threads ProduceInteger producer =  new  ProduceInteger( sharedObject ); ConsumeInteger consumer =  new  ConsumeInteger( sharedObject ); // start threads producer.start(); consumer.start(); } }  // end class SharedCell Method  main  creates a  ProduceInteger  thread and a  ConsumeInteger  thread and starts them
7. Producer/Consumer Relationship with    Thread Synchronization ,[object Object]
ProduceInteger.java Line 10 Lines 15-37 // ProduceInteger.java // Definition of threaded class ProduceInteger public class  ProduceInteger  extends  Thread { private  HoldIntegerSynchronized sharedObject; // initialize ProduceInteger thread object public  ProduceInteger( HoldIntegerSynchronized shared ) { super (  &quot;ProduceInteger&quot;  ); sharedObject = shared; } // ProduceInteger thread loops 10 times and calls  // sharedObject's setSharedInt method each time public void  run() { for  (  int  count =  1 ; count <=  10 ; count++ ) { // sleep for a random interval try  { Thread.sleep( (  int  ) ( Math.random() *  3000  ) ); } // process InterruptedException during sleep catch ( InterruptedException exception ) { System.err.println( exception.toString() ); } // call sharedObject method from this  // thread of execution sharedObject.setSharedInt( count ); } Instance variable  sharedObject  refers to object  shared Method  run  loops 10 times,  sleep ing 0-3 seconds and calling  setSharedInt System.err.println(  getName() +  &quot; finished producing values&quot;  + &quot;Terminating &quot;  + getName() ); } }  // end class ProduceInteger Thread prints that it finished
// ConsumeInteger.java // Definition of threaded class ConsumeInteger public class  ConsumeInteger  extends  Thread { private  HoldIntegerSynchronized sharedObject; // initialize ConsumerInteger thread object public  ConsumeInteger( HoldIntegerSynchronized shared ) { super (  &quot;ConsumeInteger&quot;  ); sharedObject = shared; } // ConsumeInteger thread loops until it receives 10 // from sharedObject's getSharedInt method public void  run() { int  value, sum =  0 ; do  { // sleep for a random interval try  { Thread.sleep( ( int ) ( Math.random() *  3000  ) ); } // process InterruptedException during sleep catch ( InterruptedException exception ) { System.err.println( exception.toString() ); } value = sharedObject.getSharedInt(); sum += value; }  while  ( value !=  10  ); System.err.println( getName() +  &quot; retrieved values totaling: &quot;  + sum + &quot;Terminating &quot;  + getName() ); } }  // end class ConsumeInteger Thread prints that it is done consuming Initializes  sharedObject  to refer to object  shared Method  run  contains a  do / while  structure that loops 10 times Each iteration causes the thread to  sleep  0-3 seconds Call method  getSharedInt  and assign to variable  sum
HoldIntegerSynchronized.java Line 6 Line 7 Lines 12-39 Line 14 // HoldIntegerSynchronized.java // Definition of class HoldIntegerSynchronized that // uses thread synchronization to ensure that both // threads access sharedInt at the proper times. public class  HoldIntegerSynchronized { private int  sharedInt =  -1 ; private boolean  writeable =  true ;  // condition variable // synchronized method allows only one thread at a time to  // invoke this method to set the value for a particular // HoldIntegerSynchronized object public synchronized void  setSharedInt(  int  value ) { while  ( !writeable ) {  // not the producer's turn // thread that called this method must wait  try  { wait();  } // process Interrupted exception while thread waiting catch  ( InterruptedException exception ) { exception.printStackTrace(); } } System.err.println( Thread.currentThread().getName() + &quot; setting sharedInt to &quot;  + value ); // set new sharedInt value sharedInt = value; Variable  sharedInt  represents the shared buffer Variable  writeable  is the monitor condition variable Method  setSharedInt  now  synchronized Check if  sharedInt  can be written
HoldIntegerSynchronized.java Lines 44-70 Line 46 writeable =  false ; // tell a waiting thread to become ready notify();  } // synchronized method allows only one thread at a time to  // invoke this method to get the value for a particular // HoldIntegerSynchronized object public synchronized int  getSharedInt() { while  ( writeable ) {  // not the consumer's turn // thread that called this method must wait  try  { wait(); } // process Interrupted exception while thread waiting catch  ( InterruptedException exception ) { exception.printStackTrace(); } } // indicate that producer cant store another value  // because a consumer just retrieved sharedInt value writeable =  true ; // tell a waiting thread to become ready notify();  System.err.println( Thread.currentThread().getName() + &quot; retrieving sharedInt value &quot;  + sharedInt ); Method  getSharedInt  now  synchronized Check if  sharedInt  can be read return  sharedInt; } }  // end class HoldIntegerSynchronized
SharedCell.java Lines 6-20 // SharedCell.java // Show multiple threads modifying shared object. public class  SharedCell { // execute application public static void  main( String args[] ) { HoldIntegerSynchronized sharedObject = new  HoldIntegerSynchronized(); // create threads ProduceInteger producer =  new  ProduceInteger( sharedObject ); ConsumeInteger consumer =  new  ConsumeInteger( sharedObject ); // start threads producer.start(); consumer.start(); } }  // end class SharedCell Method  main  creates a  ProduceInteger  thread and a  ConsumeInteger  thread and starts them
Program Output ProduceInteger setting sharedInt to 1 ConsumeInteger retrieving sharedInt value 1 ProduceInteger setting sharedInt to 2 ConsumeInteger retrieving sharedInt value 2 ProduceInteger setting sharedInt to 3 ConsumeInteger retrieving sharedInt value 3 ProduceInteger setting sharedInt to 4 ConsumeInteger retrieving sharedInt value 4 ProduceInteger setting sharedInt to 5 ConsumeInteger retrieving sharedInt value 5 ProduceInteger setting sharedInt to 6 ConsumeInteger retrieving sharedInt value 6 ProduceInteger setting sharedInt to 7 ConsumeInteger retrieving sharedInt value 7 ProduceInteger setting sharedInt to 8 ConsumeInteger retrieving sharedInt value 8 ProduceInteger setting sharedInt to 9 ConsumeInteger retrieving sharedInt value 9 ProduceInteger setting sharedInt to 10 ProduceInteger finished producing values Terminating ProduceInteger ConsumeInteger retrieving sharedInt value 10 ConsumeInteger retrieved values totaling: 55 Terminating ConsumeInteger   Output of numbers is properly synchronized
8. Producer/Consumer Relationship:    The Circular Buffer ,[object Object],[object Object],[object Object],[object Object]
UpdateThread.java Lines 7-24 Lines 19-22 // UpdateThread.java // Class for updating JTextArea with output. // Java extension packages import  javax.swing.*; public class  UpdateThread  extends  Thread { private  JTextArea outputArea; private  String messageToOutput; // initialize outputArea and message public  UpdateThread( JTextArea output, String message ) { outputArea = output; messageToOutput = message; } // method called to update outputArea public void  run() { outputArea.append( messageToOutput ); } }  // end class UpdateThread Class  UpdateThread  passed as a parameter to  SwingUtilities  method  invokeLater  to ensure GUI updates properly Method  run  appends text to  outputArea
ProduceInteger.java Line 9 // ProduceInteger.java import  javax.swing.*; public class  ProduceInteger  extends  Thread { private  HoldIntegerSynchronized sharedObject; private  JTextArea outputArea; // initialize ProduceInteger public  ProduceInteger( HoldIntegerSynchronized shared, JTextArea output ) { super (  &quot;ProduceInteger&quot;  ); sharedObject = shared; outputArea = output; } // ProduceInteger thread loops 10 times and calls  // sharedObject's setSharedInt method each time public void  run() { for  (  int  count =  1 ; count <=  10 ; count++ ) { // sleep for a random interval // Note: Interval shortened purposely to fill buffer try  { Thread.sleep( ( int ) ( Math.random() *  500  ) ); } Places output in  JTextArea   outputArea // process InterruptedException during sleep catch ( InterruptedException exception ) { System.err.println( exception.toString() ); } sharedObject.setSharedInt( count ); } // update Swing GUI component  SwingUtilities.invokeLater(  new  UpdateThread( outputArea, &quot;&quot;  + getName() +  &quot; finished producing values&quot;  + &quot;Terminating &quot;  + getName() +  &quot;&quot;  ) ); } }  // end class ProduceInteger SwingUtilities  method  invokeLater  ensures GUI updates properly
//ConsumeInteger.java import  javax.swing.*; public class  ConsumeInteger  extends  Thread { private  HoldIntegerSynchronized sharedObject; private  JTextArea outputArea; // initialize ConsumeInteger public  ConsumeInteger( HoldIntegerSynchronized shared, JTextArea output ){ super (  &quot;ConsumeInteger&quot;  ); sharedObject = shared; outputArea = output; } Places output in  JTextArea   outputArea // ConsumeInteger thread loops until it receives 10 // from sharedObject's getSharedInt method public void  run() { int  value, sum = 0; do  { // sleep for a random interval try  { Thread.sleep( ( int ) ( Math.random() *  3000  ) ); } // process InterruptedException during sleep catch ( InterruptedException exception ) { System.err.println( exception.toString() ); } value = sharedObject.getSharedInt(); sum += value; }  while  ( value !=  10  ); // update Swing GUI component  SwingUtilities.invokeLater(  new  UpdateThread( outputArea, &quot;&quot;  + getName() +  &quot; retrieved values totaling: &quot;  +  sum +  &quot;Terminating &quot;  + getName() +  &quot;&quot;  ) ); } }  // end class ConsumeInteger SwingUtilities  method  invokeLater  ensures GUI updates properly
//SharedCell.java // Show multiple threads modifying shared object. import  java.awt.*; import  java.awt.event.*; import  java.text.DecimalFormat; // Java extension packages import  javax.swing.*; public class  SharedCell  extends  JFrame { // set up GUI public  SharedCell() { super (  &quot;Demonstrating Thread Synchronization&quot;  ); JTextArea outputArea =  new  JTextArea(  20 ,  30  ); getContentPane().add(  new  JScrollPane( outputArea ) ); setSize(  500 ,  500  ); show(); // set up threads  HoldIntegerSynchronized sharedObject = new  HoldIntegerSynchronized( outputArea ); ProduceInteger producer =  new  ProduceInteger( sharedObject, outputArea ); ConsumeInteger consumer =  new  ConsumeInteger( sharedObject, outputArea ); // start threads producer.start(); consumer.start(); } // execute application public static void  main( String args[] ) { SharedCell application =  new  SharedCell(); application.setDefaultCloseOperation( JFrame. EXIT_ON_CLOSE  ); } }  // end class SharedCell Set up threads Set up GUI Start threads Execute application
Program Output
9. Daemon Threads ,[object Object],[object Object],[object Object],[object Object],10.  Runnable  Interface ,[object Object],[object Object],[object Object],[object Object],[object Object]

Contenu connexe

Tendances

Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaArafat Hossan
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And MultithreadingShraddha
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javajunnubabu
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVAVINOTH R
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread SynchronizationBenj Del Mundo
 
Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead ProgrammingNishant Mevawala
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threadingAPU
 
Multi threading
Multi threadingMulti threading
Multi threadinggndu
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronizationcaswenson
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded ApplicationsBharat17485
 
Thread presentation
Thread presentationThread presentation
Thread presentationAAshish Ojha
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadKartik Dube
 
Thread model of java
Thread model of javaThread model of java
Thread model of javamyrajendra
 

Tendances (19)

Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Multithreading Concepts
Multithreading ConceptsMultithreading Concepts
Multithreading Concepts
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Java threads
Java threadsJava threads
Java threads
 
Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead Programming
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded Applications
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Thread presentation
Thread presentationThread presentation
Thread presentation
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
 
Thread model of java
Thread model of javaThread model of java
Thread model of java
 

En vedette

Program na rzecz wspierania polityki w zakresie technologii informacyjnych i ...
Program na rzecz wspierania polityki w zakresie technologii informacyjnych i ...Program na rzecz wspierania polityki w zakresie technologii informacyjnych i ...
Program na rzecz wspierania polityki w zakresie technologii informacyjnych i ...kontaktowy.eu
 
Leucemia De CéLulas Pilosas
Leucemia De CéLulas PilosasLeucemia De CéLulas Pilosas
Leucemia De CéLulas Pilosastaty4u
 

En vedette (6)

Presentatie OCW
Presentatie OCWPresentatie OCW
Presentatie OCW
 
Digestivo
DigestivoDigestivo
Digestivo
 
Program na rzecz wspierania polityki w zakresie technologii informacyjnych i ...
Program na rzecz wspierania polityki w zakresie technologii informacyjnych i ...Program na rzecz wspierania polityki w zakresie technologii informacyjnych i ...
Program na rzecz wspierania polityki w zakresie technologii informacyjnych i ...
 
Present(Pbwik)I
Present(Pbwik)IPresent(Pbwik)I
Present(Pbwik)I
 
Leucemia De CéLulas Pilosas
Leucemia De CéLulas PilosasLeucemia De CéLulas Pilosas
Leucemia De CéLulas Pilosas
 
Tricoleucemia
TricoleucemiaTricoleucemia
Tricoleucemia
 

Similaire à Multithreading

Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaRaghu nath
 
Java multithreading
Java multithreadingJava multithreading
Java multithreadingMohammed625
 
Multithreading
MultithreadingMultithreading
MultithreadingF K
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptxssuserfcae42
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresHitendra Kumar
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxArulmozhivarman8
 
9.multi-threading latest(MB).ppt .
9.multi-threading latest(MB).ppt            .9.multi-threading latest(MB).ppt            .
9.multi-threading latest(MB).ppt .happycocoman
 
Multithreading
MultithreadingMultithreading
Multithreadingsagsharma
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading PresentationNeeraj Kaushik
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and ConcurrencyRajesh Ananda Kumar
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaMonika Mishra
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 

Similaire à Multithreading (20)

Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Java
JavaJava
Java
 
Java multithreading
Java multithreadingJava multithreading
Java multithreading
 
multithreading
multithreadingmultithreading
multithreading
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Java
JavaJava
Java
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data Structures
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
 
9.multi-threading latest(MB).ppt .
9.multi-threading latest(MB).ppt            .9.multi-threading latest(MB).ppt            .
9.multi-threading latest(MB).ppt .
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
MultiThreading in Python
MultiThreading in PythonMultiThreading in Python
MultiThreading in Python
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 

Plus de backdoor

Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivitybackdoor
 
Distributed Programming using RMI
 Distributed Programming using RMI Distributed Programming using RMI
Distributed Programming using RMIbackdoor
 
Programming Server side with Sevlet
 Programming Server side with Sevlet  Programming Server side with Sevlet
Programming Server side with Sevlet backdoor
 
Distributed Programming using RMI
Distributed Programming using RMIDistributed Programming using RMI
Distributed Programming using RMIbackdoor
 
Client Side Programming with Applet
Client Side Programming with AppletClient Side Programming with Applet
Client Side Programming with Appletbackdoor
 
Java Network Programming
Java Network ProgrammingJava Network Programming
Java Network Programmingbackdoor
 
Windows Programming with Swing
Windows Programming with SwingWindows Programming with Swing
Windows Programming with Swingbackdoor
 
Windows Programming with AWT
Windows Programming with AWTWindows Programming with AWT
Windows Programming with AWTbackdoor
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Javabackdoor
 
IO and serialization
IO and serializationIO and serialization
IO and serializationbackdoor
 
Exception Handling
Exception HandlingException Handling
Exception Handlingbackdoor
 
Java Intro
Java IntroJava Intro
Java Introbackdoor
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 
AWT Program output
AWT Program outputAWT Program output
AWT Program outputbackdoor
 
Data Security
Data SecurityData Security
Data Securitybackdoor
 
Ne Course Part One
Ne Course Part OneNe Course Part One
Ne Course Part Onebackdoor
 
Ne Course Part Two
Ne Course Part TwoNe Course Part Two
Ne Course Part Twobackdoor
 
Security Policy Checklist
Security Policy ChecklistSecurity Policy Checklist
Security Policy Checklistbackdoor
 

Plus de backdoor (20)

Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
Distributed Programming using RMI
 Distributed Programming using RMI Distributed Programming using RMI
Distributed Programming using RMI
 
Programming Server side with Sevlet
 Programming Server side with Sevlet  Programming Server side with Sevlet
Programming Server side with Sevlet
 
Distributed Programming using RMI
Distributed Programming using RMIDistributed Programming using RMI
Distributed Programming using RMI
 
Client Side Programming with Applet
Client Side Programming with AppletClient Side Programming with Applet
Client Side Programming with Applet
 
Java Network Programming
Java Network ProgrammingJava Network Programming
Java Network Programming
 
Windows Programming with Swing
Windows Programming with SwingWindows Programming with Swing
Windows Programming with Swing
 
Windows Programming with AWT
Windows Programming with AWTWindows Programming with AWT
Windows Programming with AWT
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
IO and serialization
IO and serializationIO and serialization
IO and serialization
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java Intro
Java IntroJava Intro
Java Intro
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
AWT Program output
AWT Program outputAWT Program output
AWT Program output
 
Net Man
Net ManNet Man
Net Man
 
Data Security
Data SecurityData Security
Data Security
 
Ne Course Part One
Ne Course Part OneNe Course Part One
Ne Course Part One
 
Ne Course Part Two
Ne Course Part TwoNe Course Part Two
Ne Course Part Two
 
Net Sec
Net SecNet Sec
Net Sec
 
Security Policy Checklist
Security Policy ChecklistSecurity Policy Checklist
Security Policy Checklist
 

Dernier

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 

Dernier (20)

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 

Multithreading

  • 1. Multi-threading U Nyein Oo COO/Director(IT) Myanma Computer Co., Ltd IADCS Diploma Course
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13. 3. Thread States: Life Cycle of a Thread
  • 14.
  • 15. ThreadTester.java //ThreadTester.java public class ThreadTester { // create and start threads public static void main( String args[] ) { PrintThread thread1, thread2, thread3, thread4; // create four PrintThread objects thread1 = new PrintThread( &quot;thread1&quot; ); thread2 = new PrintThread( &quot;thread2&quot; ); thread3 = new PrintThread( &quot;thread3&quot; ); thread4 = new PrintThread( &quot;thread4&quot; ); System.err.println( &quot;Starting threads&quot; ); // start executing PrintThreads thread1.start(); thread2.start(); thread3.start(); thread4.start(); System.err.println( &quot;Threads started&quot; ); } } // end class ThreadTester Class ThreadTester creates four PrintThread s and calls their start methods
  • 16. ThreadTester.java Lines 33-71 Lines 38-48 Lines 51-69 class PrintThread extends Thread { private int sleepTime; // PrintThread constructor assigns name to thread // by calling superclass Thread constructor public PrintThread( String name ) { super ( name ); // sleep between 0 and 5 seconds sleepTime = ( int ) ( Math.random() * 5000 ); // display name and sleepTime System.err.println( &quot;Name: &quot; + getName() + &quot;; sleep: &quot; + sleepTime ); } // control thread's execution public void run() { // put thread to sleep for a random interval try { System.err.println( getName() + &quot; going to sleep&quot; ); // put thread to sleep Thread.sleep( sleepTime ); } Thread run method prints a String saying the thread is going to sleep and thread sleeps // if thread interrupted during sleep, catch exception // and display error message catch ( InterruptedException interruptedException ) { System.err.println( interruptedException.toString() ); } // print thread name System.err.println( getName() + &quot; done sleeping&quot; ); } } // end class PrintThread Thread prints name when done sleeping PrintThread inherits from Thread so each object of the class can execute in parallel Constructor initializes sleepTime to be 0 to 4.999 seconds and outputs name and value of sleepTime
  • 17.
  • 18.
  • 19. ProduceInteger.java Line 10 Lines 15-37 //ProduceInteger.java public class ProduceInteger extends Thread { private HoldIntegerUnsynchronized sharedObject; // initialize ProduceInteger thread object public ProduceInteger( HoldIntegerUnsynchronized shared ) { super ( &quot;ProduceInteger&quot; ); sharedObject = shared; } // ProduceInteger thread loops 10 times and calls // sharedObject's setSharedInt method each time public void run() { for ( int count = 1 ; count <= 10 ; count++ ) { // sleep for a random interval try { Thread.sleep( ( int ) ( Math.random() * 3000 ) ); } // process InterruptedException during sleep catch ( InterruptedException exception ) { System.err.println( exception.toString() ); } // call sharedObject method from this // thread of execution sharedObject.setSharedInt( count ); } Method run loops 10 times, sleep ing 0-3 seconds and calling setSharedInt System.err.println( getName() + &quot; finished producing values&quot; + &quot;Terminating &quot; + getName() ); } } // end class ProduceInteger Thread prints that it finished Instance variable sharedObject refers to object shared
  • 20. ConsumeInteger.java Line 10 Lines 15-39 Line 23 Lines 31-32 //ConsumeInteger.java public class ConsumeInteger extends Thread { private HoldIntegerUnsynchronized sharedObject; // initialize ConsumerInteger thread object public ConsumeInteger( HoldIntegerUnsynchronized shared ) { super ( &quot;ConsumeInteger&quot; ); sharedObject = shared; } // ConsumeInteger thread loops until it receives 10 // from sharedObject's getSharedInt method public void run() { int value, sum = 0 ; do { // sleep for a random interval try { Thread.sleep( ( int ) ( Math.random() * 3000 ) ); } // process InterruptedException during sleep catch ( InterruptedException exception ) { System.err.println( exception.toString() ); } value = sharedObject.getSharedInt(); sum += value; } while ( value != 10 ); Each iteration causes the thread to sleep 0-3 seconds Call method getSharedInt and assign to variable sum System.err.println( getName() + &quot; retrieved values totaling: &quot; + sum + &quot;Terminating &quot; + getName() ); } } // end class ConsumeInteger Thread prints that it is done consuming Initializes sharedObject to refer to object shared Method run contains a do / while structure that loops 10 times
  • 21. HoldIntegerUnsynchronized.java Line 4 Lines 7-13 Lines 16-22 // HoldIntegerUnsynchronized.java // Definition of class HoldIntegerUnsynchronized. public class HoldIntegerUnsynchronized { private int sharedInt = -1 ; // unsynchronized method to place value in sharedInt public void setSharedInt( int value ) { System.err.println( Thread.currentThread().getName() + &quot; setting sharedInt to &quot; + value ); sharedInt = value; } // unsynchronized method return sharedInt's value public int getSharedInt() { System.err.println( Thread.currentThread().getName() + &quot; retrieving sharedInt value &quot; + sharedInt ); return sharedInt; } } // end class HoldIntegerUnsynchronized Instance variable sharedInt is the shared buffer Method setSharedInt not synchronized Method getSharedInt not synchronized
  • 22. SharedCell.java Lines 6-20 //SharedCell.java // Show multiple threads modifying shared object. public class SharedCell { // execute application public static void main( String args[] ) { HoldIntegerUnsynchronized sharedObject = new HoldIntegerUnsynchronized(); // create threads ProduceInteger producer = new ProduceInteger( sharedObject ); ConsumeInteger consumer = new ConsumeInteger( sharedObject ); // start threads producer.start(); consumer.start(); } } // end class SharedCell Method main creates a ProduceInteger thread and a ConsumeInteger thread and starts them
  • 23.
  • 24. ProduceInteger.java Line 10 Lines 15-37 // ProduceInteger.java // Definition of threaded class ProduceInteger public class ProduceInteger extends Thread { private HoldIntegerSynchronized sharedObject; // initialize ProduceInteger thread object public ProduceInteger( HoldIntegerSynchronized shared ) { super ( &quot;ProduceInteger&quot; ); sharedObject = shared; } // ProduceInteger thread loops 10 times and calls // sharedObject's setSharedInt method each time public void run() { for ( int count = 1 ; count <= 10 ; count++ ) { // sleep for a random interval try { Thread.sleep( ( int ) ( Math.random() * 3000 ) ); } // process InterruptedException during sleep catch ( InterruptedException exception ) { System.err.println( exception.toString() ); } // call sharedObject method from this // thread of execution sharedObject.setSharedInt( count ); } Instance variable sharedObject refers to object shared Method run loops 10 times, sleep ing 0-3 seconds and calling setSharedInt System.err.println( getName() + &quot; finished producing values&quot; + &quot;Terminating &quot; + getName() ); } } // end class ProduceInteger Thread prints that it finished
  • 25. // ConsumeInteger.java // Definition of threaded class ConsumeInteger public class ConsumeInteger extends Thread { private HoldIntegerSynchronized sharedObject; // initialize ConsumerInteger thread object public ConsumeInteger( HoldIntegerSynchronized shared ) { super ( &quot;ConsumeInteger&quot; ); sharedObject = shared; } // ConsumeInteger thread loops until it receives 10 // from sharedObject's getSharedInt method public void run() { int value, sum = 0 ; do { // sleep for a random interval try { Thread.sleep( ( int ) ( Math.random() * 3000 ) ); } // process InterruptedException during sleep catch ( InterruptedException exception ) { System.err.println( exception.toString() ); } value = sharedObject.getSharedInt(); sum += value; } while ( value != 10 ); System.err.println( getName() + &quot; retrieved values totaling: &quot; + sum + &quot;Terminating &quot; + getName() ); } } // end class ConsumeInteger Thread prints that it is done consuming Initializes sharedObject to refer to object shared Method run contains a do / while structure that loops 10 times Each iteration causes the thread to sleep 0-3 seconds Call method getSharedInt and assign to variable sum
  • 26. HoldIntegerSynchronized.java Line 6 Line 7 Lines 12-39 Line 14 // HoldIntegerSynchronized.java // Definition of class HoldIntegerSynchronized that // uses thread synchronization to ensure that both // threads access sharedInt at the proper times. public class HoldIntegerSynchronized { private int sharedInt = -1 ; private boolean writeable = true ; // condition variable // synchronized method allows only one thread at a time to // invoke this method to set the value for a particular // HoldIntegerSynchronized object public synchronized void setSharedInt( int value ) { while ( !writeable ) { // not the producer's turn // thread that called this method must wait try { wait(); } // process Interrupted exception while thread waiting catch ( InterruptedException exception ) { exception.printStackTrace(); } } System.err.println( Thread.currentThread().getName() + &quot; setting sharedInt to &quot; + value ); // set new sharedInt value sharedInt = value; Variable sharedInt represents the shared buffer Variable writeable is the monitor condition variable Method setSharedInt now synchronized Check if sharedInt can be written
  • 27. HoldIntegerSynchronized.java Lines 44-70 Line 46 writeable = false ; // tell a waiting thread to become ready notify(); } // synchronized method allows only one thread at a time to // invoke this method to get the value for a particular // HoldIntegerSynchronized object public synchronized int getSharedInt() { while ( writeable ) { // not the consumer's turn // thread that called this method must wait try { wait(); } // process Interrupted exception while thread waiting catch ( InterruptedException exception ) { exception.printStackTrace(); } } // indicate that producer cant store another value // because a consumer just retrieved sharedInt value writeable = true ; // tell a waiting thread to become ready notify(); System.err.println( Thread.currentThread().getName() + &quot; retrieving sharedInt value &quot; + sharedInt ); Method getSharedInt now synchronized Check if sharedInt can be read return sharedInt; } } // end class HoldIntegerSynchronized
  • 28. SharedCell.java Lines 6-20 // SharedCell.java // Show multiple threads modifying shared object. public class SharedCell { // execute application public static void main( String args[] ) { HoldIntegerSynchronized sharedObject = new HoldIntegerSynchronized(); // create threads ProduceInteger producer = new ProduceInteger( sharedObject ); ConsumeInteger consumer = new ConsumeInteger( sharedObject ); // start threads producer.start(); consumer.start(); } } // end class SharedCell Method main creates a ProduceInteger thread and a ConsumeInteger thread and starts them
  • 29. Program Output ProduceInteger setting sharedInt to 1 ConsumeInteger retrieving sharedInt value 1 ProduceInteger setting sharedInt to 2 ConsumeInteger retrieving sharedInt value 2 ProduceInteger setting sharedInt to 3 ConsumeInteger retrieving sharedInt value 3 ProduceInteger setting sharedInt to 4 ConsumeInteger retrieving sharedInt value 4 ProduceInteger setting sharedInt to 5 ConsumeInteger retrieving sharedInt value 5 ProduceInteger setting sharedInt to 6 ConsumeInteger retrieving sharedInt value 6 ProduceInteger setting sharedInt to 7 ConsumeInteger retrieving sharedInt value 7 ProduceInteger setting sharedInt to 8 ConsumeInteger retrieving sharedInt value 8 ProduceInteger setting sharedInt to 9 ConsumeInteger retrieving sharedInt value 9 ProduceInteger setting sharedInt to 10 ProduceInteger finished producing values Terminating ProduceInteger ConsumeInteger retrieving sharedInt value 10 ConsumeInteger retrieved values totaling: 55 Terminating ConsumeInteger Output of numbers is properly synchronized
  • 30.
  • 31. UpdateThread.java Lines 7-24 Lines 19-22 // UpdateThread.java // Class for updating JTextArea with output. // Java extension packages import javax.swing.*; public class UpdateThread extends Thread { private JTextArea outputArea; private String messageToOutput; // initialize outputArea and message public UpdateThread( JTextArea output, String message ) { outputArea = output; messageToOutput = message; } // method called to update outputArea public void run() { outputArea.append( messageToOutput ); } } // end class UpdateThread Class UpdateThread passed as a parameter to SwingUtilities method invokeLater to ensure GUI updates properly Method run appends text to outputArea
  • 32. ProduceInteger.java Line 9 // ProduceInteger.java import javax.swing.*; public class ProduceInteger extends Thread { private HoldIntegerSynchronized sharedObject; private JTextArea outputArea; // initialize ProduceInteger public ProduceInteger( HoldIntegerSynchronized shared, JTextArea output ) { super ( &quot;ProduceInteger&quot; ); sharedObject = shared; outputArea = output; } // ProduceInteger thread loops 10 times and calls // sharedObject's setSharedInt method each time public void run() { for ( int count = 1 ; count <= 10 ; count++ ) { // sleep for a random interval // Note: Interval shortened purposely to fill buffer try { Thread.sleep( ( int ) ( Math.random() * 500 ) ); } Places output in JTextArea outputArea // process InterruptedException during sleep catch ( InterruptedException exception ) { System.err.println( exception.toString() ); } sharedObject.setSharedInt( count ); } // update Swing GUI component SwingUtilities.invokeLater( new UpdateThread( outputArea, &quot;&quot; + getName() + &quot; finished producing values&quot; + &quot;Terminating &quot; + getName() + &quot;&quot; ) ); } } // end class ProduceInteger SwingUtilities method invokeLater ensures GUI updates properly
  • 33. //ConsumeInteger.java import javax.swing.*; public class ConsumeInteger extends Thread { private HoldIntegerSynchronized sharedObject; private JTextArea outputArea; // initialize ConsumeInteger public ConsumeInteger( HoldIntegerSynchronized shared, JTextArea output ){ super ( &quot;ConsumeInteger&quot; ); sharedObject = shared; outputArea = output; } Places output in JTextArea outputArea // ConsumeInteger thread loops until it receives 10 // from sharedObject's getSharedInt method public void run() { int value, sum = 0; do { // sleep for a random interval try { Thread.sleep( ( int ) ( Math.random() * 3000 ) ); } // process InterruptedException during sleep catch ( InterruptedException exception ) { System.err.println( exception.toString() ); } value = sharedObject.getSharedInt(); sum += value; } while ( value != 10 ); // update Swing GUI component SwingUtilities.invokeLater( new UpdateThread( outputArea, &quot;&quot; + getName() + &quot; retrieved values totaling: &quot; + sum + &quot;Terminating &quot; + getName() + &quot;&quot; ) ); } } // end class ConsumeInteger SwingUtilities method invokeLater ensures GUI updates properly
  • 34. //SharedCell.java // Show multiple threads modifying shared object. import java.awt.*; import java.awt.event.*; import java.text.DecimalFormat; // Java extension packages import javax.swing.*; public class SharedCell extends JFrame { // set up GUI public SharedCell() { super ( &quot;Demonstrating Thread Synchronization&quot; ); JTextArea outputArea = new JTextArea( 20 , 30 ); getContentPane().add( new JScrollPane( outputArea ) ); setSize( 500 , 500 ); show(); // set up threads HoldIntegerSynchronized sharedObject = new HoldIntegerSynchronized( outputArea ); ProduceInteger producer = new ProduceInteger( sharedObject, outputArea ); ConsumeInteger consumer = new ConsumeInteger( sharedObject, outputArea ); // start threads producer.start(); consumer.start(); } // execute application public static void main( String args[] ) { SharedCell application = new SharedCell(); application.setDefaultCloseOperation( JFrame. EXIT_ON_CLOSE ); } } // end class SharedCell Set up threads Set up GUI Start threads Execute application
  • 36.