SlideShare a Scribd company logo
Multi-threading U Nyein Oo COO/Director(IT) Myanma Computer Co., Ltd IADCS Diploma Course
What’s a Thread? A process is an executing program  memory allocated by OS usually no memory sharing between processes  A thread is a single sequential flow of control  runs in the address space of a process  has its own program counter  and  its own stack frame  A thread is a path of execution through a program . Single threaded programs->one path of execution Multiple threaded programs -> two or more Threads run in methods or constructors. The threads go into the methods and follow their instructions.  1. Introduction
Initial Remarks about Threads Cheaper in computing resources and creation , a thread can only act within a single process. Java threads  are  built into the language Threads are "light-weight" processes (unlike UNIX processes), which communicate by a combination of shared memory and message passing . Sharing resources between threads is done with synchronization. This communication mechanism is employed naturally by Java  Java threads are based on a locking mechanism using monitors for synchronization 1. Introduction (cont;)
Some spesific uses for threads Long initiations  (in applets that take a while to initialize) Repetitive or timed tasks (animations) Asynchronous events (event handling such as a mouse click) Multiple Tasks (To do more than one thing at once) Java applications and applets are naturally threaded . 1. Introduction (cont;)
Multitasking vs. Multithreading Multitasking operating systems run multiple programs simultaneously. O.S is reponsible for splitting time  the time among the different programs that are running Once systems allowed different users to run programs at the same time it was a short step to letting the same user run multiple programs simultaneously . Multithreading enables users and programs to accomplish multiple simultaneous tasks. 1. Introduction (cont;)
Overview of Multitasking Each of programs has at least one thread within it. Single thread in a single process Process begins execution at a well-known point.  (i.e main () ) Execution of statements follow a predefined order. During execution process has access to certain data:  thread’s stack->local variables    object references->instance variables class or object references-> static variables 1. Introduction (cont;)
Processes in a Multitasking Environment Data within processes is seperated; separate stack for local variables and  data area for objects  1. Introduction (cont;)
Overview of Multithreading Analogy : thread   process Multiple thread running within a single instance of  JVM   multiple processes within an OS 1. Introduction (cont;)
Properties of Multiple Threads Each thread begins execution at a well-defined location. Code execution from starting location in a predefined sequence. Each thread executes code independently of others in the prg. Also mechanisms of threads that allow cooperation. The threads appear to have  a certain degree of simultaneous execution. Access  to various types of data Each thread is separate, so that local variables in the methods  are seperate.   Objects and their instance variables   can be shared btw threads in a Java program . Static variables are  automatically shared  . 1. Introduction (cont;)
Possible Uses for Multithreading In general, you’ll have some part of your program tied to a particular event or resource   (and you don’t want to hang up the rest of your program because of that). So you create a thread associated with that event or   resource and let it run independently of the main   program. A good example  could be  a “quit” button you don’t want to be forced to poll the quit button in every   piece of code you   write in your program and yet you want the quit button to be responsive, as if   you were   checking it regularly. In fact, one of the most immediately compelling   reasons for multithreading is to produce a responsive   user interface. 1. Introduction (cont;)
Class  Thread :  An Overview of the  Thread  Methods Class  Thread  constructors public  Thread( String threadName ) public  Thread() Code for thread in thread’s  run  method Method  sleep  makes thread inactive Method  interrupt  interrupts a running thread Method  isAlive  checks status of a thread Method  setName  sets a thread’s name Method  join Waits for thread to finish and continues from current thread
3. Threaded States: Life Cycle of a Thread Thread states Born state Thread was just created Ready state Thread’s  start  method invoked Thread can now execute Running state Thread is assigned a processor and running Dead state Thread has completed or exited Eventually disposed of by system
3. Thread States: Life Cycle of a Thread
4. Thread Priorities and Thread Scheduling Java thread priority Priority in range 1-10 Timeslicing Each thread assigned time on the processor by quantum Keeps highest priority threads running One can implement threads in two ways:  First, by subclassing the Thread class  Second, by implementing the Runnable interface  The Runnable interface allows you to add threading to a class which   cannot conveniently extend Thread. A class that implements the Runnable interface (including the Thread class itself) must implement the run() method containing the "body" of the thread.
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(  "\nStarting threads"  ); // start executing PrintThreads thread1.start(); thread2.start(); thread3.start(); thread4.start(); System.err.println(  "Threads started\n"  ); } }  // 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 Java uses monitors for thread synchronization The  sychronized  keyword Every  synchronized  method of an object has a monitor One thread inside a  synchronized  method at a time All other threads block until method finishes Next highest priority thread runs when method finishes
6. Producer/Consumer Relationship without    Synchronization Buffer Shared memory region Producer thread Calls produce method to add item to buffer Calls  wait  if consumer has not read last message in buffer Writes to empty buffer and calls  notify  for consumer Consumer thread Reads message from buffer Calls  wait  if buffer empty Synchronize threads to avoid corrupted data
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;\nTerminating &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;\nTerminating &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 Synchronize threads to ensure correct data
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;\nTerminating &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;\nTerminating &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 Circular buffer Multiple memory cells Produce item if one or more empty cells Consume item if one or more filled cells
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;\n&quot;  + getName() +  &quot; finished producing values&quot;  + &quot;\nTerminating &quot;  + getName() +  &quot;\n&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;\n&quot;  + getName() +  &quot; retrieved values totaling: &quot;  +  sum +  &quot;\nTerminating &quot;  + getName() +  &quot;\n&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 Runs for benefit of other threads Do not prevent program from terminating Garbage is a daemon thread Set daemon thread with method  setDaemon 10.  Runnable  Interface Multithreading in a class that extends a class A class cannot extend more than one class Implements  Runnable  for multithreading support Runnable  object grouped with a  Thread  object Program – RandomCharacter.java will be shown it

More Related Content

PDF
What is Multithreading In Python | Python Multithreading Tutorial | Edureka
PPTX
Java Thread & Multithreading
PPTX
Multithread Programing in Java
PPT
Chap2 2 1
PPTX
Multi-threaded Programming in JAVA
PPTX
PPSX
Multithreading in-java
PPT
Java Multithreading
What is Multithreading In Python | Python Multithreading Tutorial | Edureka
Java Thread & Multithreading
Multithread Programing in Java
Chap2 2 1
Multi-threaded Programming in JAVA
Multithreading in-java
Java Multithreading

What's hot (19)

PPTX
Multithreading in java
PPT
Java And Multithreading
ODP
Multithreading Concepts
PPTX
Multithreading in java
PPTX
MULTI THREADING IN JAVA
PDF
Java Thread Synchronization
PDF
Java threads
PPTX
Java Multi Thead Programming
PPT
12 multi-threading
 
PPTX
Multi threading
PPT
Thread model in java
PDF
Threads concept in java
PPT
Learning Java 3 – Threads and Synchronization
PPT
Developing Multithreaded Applications
PPTX
Multithreading in java
PPTX
Thread presentation
PPT
Java Threads and Concurrency
PDF
Multithreading Introduction and Lifecyle of thread
PPTX
Thread model of java
Multithreading in java
Java And Multithreading
Multithreading Concepts
Multithreading in java
MULTI THREADING IN JAVA
Java Thread Synchronization
Java threads
Java Multi Thead Programming
12 multi-threading
 
Multi threading
Thread model in java
Threads concept in java
Learning Java 3 – Threads and Synchronization
Developing Multithreaded Applications
Multithreading in java
Thread presentation
Java Threads and Concurrency
Multithreading Introduction and Lifecyle of thread
Thread model of java
Ad

Viewers also liked (6)

PPT
Presentatie OCW
PPT
Digestivo
PDF
Program na rzecz wspierania polityki w zakresie technologii informacyjnych i ...
PPT
Present(Pbwik)I
PPT
Leucemia De CéLulas Pilosas
PPTX
Tricoleucemia
Presentatie OCW
Digestivo
Program na rzecz wspierania polityki w zakresie technologii informacyjnych i ...
Present(Pbwik)I
Leucemia De CéLulas Pilosas
Tricoleucemia
Ad

Similar to Multithreading (20)

PPTX
Threads in Java
PPTX
Chap3 multi threaded programming
PPT
Java Performance, Threading and Concurrent Data Structures
PPT
Md09 multithreading
PPTX
Multithreading in java
PPTX
Multithreading in java
PPTX
DOCX
Module - 5 merged.docx notes about engineering subjects java
PDF
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
PPTX
Multithreading in Java Object Oriented Programming language
PPTX
Multithreading in java
PPTX
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
PDF
Threads
PPTX
MSBTE Computer Engineering JPR java. multi. threading.pptx
PPTX
Multithreading
PPTX
Thread priorities in java
PPTX
Java programming PPT. .pptx
PPTX
multithreading to be used in java with good programs.pptx
PPTX
multithreading,thread and processinjava-210302183809.pptx
PPT
Session 7_MULTITHREADING in java example.ppt
Threads in Java
Chap3 multi threaded programming
Java Performance, Threading and Concurrent Data Structures
Md09 multithreading
Multithreading in java
Multithreading in java
Module - 5 merged.docx notes about engineering subjects java
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
Multithreading in Java Object Oriented Programming language
Multithreading in java
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
Threads
MSBTE Computer Engineering JPR java. multi. threading.pptx
Multithreading
Thread priorities in java
Java programming PPT. .pptx
multithreading to be used in java with good programs.pptx
multithreading,thread and processinjava-210302183809.pptx
Session 7_MULTITHREADING in java example.ppt

More from backdoor (20)

PPT
Java Database Connectivity
PPT
Distributed Programming using RMI
PPT
Programming Server side with Sevlet
PPT
Distributed Programming using RMI
PPT
Client Side Programming with Applet
PPT
Java Network Programming
PPT
Windows Programming with Swing
PPT
Windows Programming with AWT
PPT
Object and Classes in Java
PPT
IO and serialization
PPT
Exception Handling
PPT
Java Intro
PPT
Object Oriented Programming with Java
PPT
AWT Program output
PPT
Net Man
PPT
Data Security
PPT
Ne Course Part One
PPT
Ne Course Part Two
PPT
Net Sec
PDF
Security Policy Checklist
Java Database Connectivity
Distributed Programming using RMI
Programming Server side with Sevlet
Distributed Programming using RMI
Client Side Programming with Applet
Java Network Programming
Windows Programming with Swing
Windows Programming with AWT
Object and Classes in Java
IO and serialization
Exception Handling
Java Intro
Object Oriented Programming with Java
AWT Program output
Net Man
Data Security
Ne Course Part One
Ne Course Part Two
Net Sec
Security Policy Checklist

Recently uploaded (20)

PPTX
Cloud computing and distributed systems.
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Electronic commerce courselecture one. Pdf
PDF
cuic standard and advanced reporting.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Transforming Manufacturing operations through Intelligent Integrations
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Big Data Technologies - Introduction.pptx
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Empathic Computing: Creating Shared Understanding
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Chapter 2 Digital Image Fundamentals.pdf
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Understanding_Digital_Forensics_Presentation.pptx
Cloud computing and distributed systems.
GamePlan Trading System Review: Professional Trader's Honest Take
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Electronic commerce courselecture one. Pdf
cuic standard and advanced reporting.pdf
MYSQL Presentation for SQL database connectivity
Transforming Manufacturing operations through Intelligent Integrations
Review of recent advances in non-invasive hemoglobin estimation
Big Data Technologies - Introduction.pptx
Dropbox Q2 2025 Financial Results & Investor Presentation
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Empathic Computing: Creating Shared Understanding
The Rise and Fall of 3GPP – Time for a Sabbatical?
Chapter 3 Spatial Domain Image Processing.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Chapter 2 Digital Image Fundamentals.pdf
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Understanding_Digital_Forensics_Presentation.pptx

Multithreading

  • 1. Multi-threading U Nyein Oo COO/Director(IT) Myanma Computer Co., Ltd IADCS Diploma Course
  • 2. What’s a Thread? A process is an executing program memory allocated by OS usually no memory sharing between processes A thread is a single sequential flow of control runs in the address space of a process has its own program counter and its own stack frame A thread is a path of execution through a program . Single threaded programs->one path of execution Multiple threaded programs -> two or more Threads run in methods or constructors. The threads go into the methods and follow their instructions. 1. Introduction
  • 3. Initial Remarks about Threads Cheaper in computing resources and creation , a thread can only act within a single process. Java threads are built into the language Threads are &quot;light-weight&quot; processes (unlike UNIX processes), which communicate by a combination of shared memory and message passing . Sharing resources between threads is done with synchronization. This communication mechanism is employed naturally by Java Java threads are based on a locking mechanism using monitors for synchronization 1. Introduction (cont;)
  • 4. Some spesific uses for threads Long initiations (in applets that take a while to initialize) Repetitive or timed tasks (animations) Asynchronous events (event handling such as a mouse click) Multiple Tasks (To do more than one thing at once) Java applications and applets are naturally threaded . 1. Introduction (cont;)
  • 5. Multitasking vs. Multithreading Multitasking operating systems run multiple programs simultaneously. O.S is reponsible for splitting time the time among the different programs that are running Once systems allowed different users to run programs at the same time it was a short step to letting the same user run multiple programs simultaneously . Multithreading enables users and programs to accomplish multiple simultaneous tasks. 1. Introduction (cont;)
  • 6. Overview of Multitasking Each of programs has at least one thread within it. Single thread in a single process Process begins execution at a well-known point. (i.e main () ) Execution of statements follow a predefined order. During execution process has access to certain data: thread’s stack->local variables object references->instance variables class or object references-> static variables 1. Introduction (cont;)
  • 7. Processes in a Multitasking Environment Data within processes is seperated; separate stack for local variables and data area for objects 1. Introduction (cont;)
  • 8. Overview of Multithreading Analogy : thread  process Multiple thread running within a single instance of JVM  multiple processes within an OS 1. Introduction (cont;)
  • 9. Properties of Multiple Threads Each thread begins execution at a well-defined location. Code execution from starting location in a predefined sequence. Each thread executes code independently of others in the prg. Also mechanisms of threads that allow cooperation. The threads appear to have a certain degree of simultaneous execution. Access to various types of data Each thread is separate, so that local variables in the methods are seperate. Objects and their instance variables can be shared btw threads in a Java program . Static variables are automatically shared . 1. Introduction (cont;)
  • 10. Possible Uses for Multithreading In general, you’ll have some part of your program tied to a particular event or resource (and you don’t want to hang up the rest of your program because of that). So you create a thread associated with that event or resource and let it run independently of the main program. A good example could be a “quit” button you don’t want to be forced to poll the quit button in every piece of code you write in your program and yet you want the quit button to be responsive, as if you were checking it regularly. In fact, one of the most immediately compelling reasons for multithreading is to produce a responsive user interface. 1. Introduction (cont;)
  • 11. Class Thread : An Overview of the Thread Methods Class Thread constructors public Thread( String threadName ) public Thread() Code for thread in thread’s run method Method sleep makes thread inactive Method interrupt interrupts a running thread Method isAlive checks status of a thread Method setName sets a thread’s name Method join Waits for thread to finish and continues from current thread
  • 12. 3. Threaded States: Life Cycle of a Thread Thread states Born state Thread was just created Ready state Thread’s start method invoked Thread can now execute Running state Thread is assigned a processor and running Dead state Thread has completed or exited Eventually disposed of by system
  • 13. 3. Thread States: Life Cycle of a Thread
  • 14. 4. Thread Priorities and Thread Scheduling Java thread priority Priority in range 1-10 Timeslicing Each thread assigned time on the processor by quantum Keeps highest priority threads running One can implement threads in two ways: First, by subclassing the Thread class Second, by implementing the Runnable interface The Runnable interface allows you to add threading to a class which cannot conveniently extend Thread. A class that implements the Runnable interface (including the Thread class itself) must implement the run() method containing the &quot;body&quot; of the thread.
  • 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;\nStarting threads&quot; ); // start executing PrintThreads thread1.start(); thread2.start(); thread3.start(); thread4.start(); System.err.println( &quot;Threads started\n&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. 5. Thread Synchronization Java uses monitors for thread synchronization The sychronized keyword Every synchronized method of an object has a monitor One thread inside a synchronized method at a time All other threads block until method finishes Next highest priority thread runs when method finishes
  • 18. 6. Producer/Consumer Relationship without Synchronization Buffer Shared memory region Producer thread Calls produce method to add item to buffer Calls wait if consumer has not read last message in buffer Writes to empty buffer and calls notify for consumer Consumer thread Reads message from buffer Calls wait if buffer empty Synchronize threads to avoid corrupted data
  • 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;\nTerminating &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;\nTerminating &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. 7. Producer/Consumer Relationship with Thread Synchronization Synchronize threads to ensure correct data
  • 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;\nTerminating &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;\nTerminating &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. 8. Producer/Consumer Relationship: The Circular Buffer Circular buffer Multiple memory cells Produce item if one or more empty cells Consume item if one or more filled cells
  • 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;\n&quot; + getName() + &quot; finished producing values&quot; + &quot;\nTerminating &quot; + getName() + &quot;\n&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;\n&quot; + getName() + &quot; retrieved values totaling: &quot; + sum + &quot;\nTerminating &quot; + getName() + &quot;\n&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. 9. Daemon Threads Runs for benefit of other threads Do not prevent program from terminating Garbage is a daemon thread Set daemon thread with method setDaemon 10. Runnable Interface Multithreading in a class that extends a class A class cannot extend more than one class Implements Runnable for multithreading support Runnable object grouped with a Thread object Program – RandomCharacter.java will be shown it