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
Ad

More Related Content

What's hot (19)

Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Arafat Hossan
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
Multithreading Concepts
Multithreading ConceptsMultithreading Concepts
Multithreading Concepts
Arvind Krishnaa
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
junnubabu
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
 
Java threads
Java threadsJava threads
Java threads
Prabhakaran V M
 
Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead Programming
Nishant Mevawala
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
APU
 
Multi threading
Multi threadingMulti threading
Multi threading
gndu
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
AmbigaMurugesan
 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
Muthukumaran Subramanian
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
caswenson
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded Applications
Bharat17485
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Lovely Professional University
 
Thread presentation
Thread presentationThread presentation
Thread presentation
AAshish Ojha
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
Sunil OS
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
Thread model of java
Thread model of javaThread model of java
Thread model of java
myrajendra
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Arafat Hossan
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
junnubabu
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
 
Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead Programming
Nishant Mevawala
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
APU
 
Multi threading
Multi threadingMulti threading
Multi threading
gndu
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
caswenson
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded Applications
Bharat17485
 
Thread presentation
Thread presentationThread presentation
Thread presentation
AAshish Ojha
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
Sunil OS
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
Kartik Dube
 
Thread model of java
Thread model of javaThread model of java
Thread model of java
myrajendra
 

Viewers also liked (6)

Presentatie OCW
Presentatie OCWPresentatie OCW
Presentatie OCW
Sebastiaan ter Burg
 
Digestivo
DigestivoDigestivo
Digestivo
Mnuel Castellano
 
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
 
Present(Pbwik)I
Present(Pbwik)IPresent(Pbwik)I
Present(Pbwik)I
guestabf1e5
 
Leucemia De CéLulas Pilosas
Leucemia De CéLulas PilosasLeucemia De CéLulas Pilosas
Leucemia De CéLulas Pilosas
taty4u
 
Tricoleucemia
TricoleucemiaTricoleucemia
Tricoleucemia
MDFtrabajo
 
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 Pilosas
taty4u
 
Ad

Similar to Multithreading (20)

Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Raghu nath
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
Rakesh Madugula
 
Java
JavaJava
Java
mdfkhan625
 
Java multithreading
Java multithreadingJava multithreading
Java multithreading
Mohammed625
 
multithreading
multithreadingmultithreading
multithreading
Rajkattamuri
 
Multithreading
MultithreadingMultithreading
Multithreading
F K
 
Java
JavaJava
Java
Khasim Cise
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
ssuserfcae42
 
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
Hitendra Kumar
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
PreetiDixit22
 
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
Arulmozhivarman8
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
Himanshu Rajput
 
Java Multithreading Interview Questions PDF By ScholarHat
Java Multithreading Interview Questions PDF By ScholarHatJava Multithreading Interview Questions PDF By ScholarHat
Java Multithreading Interview Questions PDF By ScholarHat
Scholarhat
 
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
Multithreading
sagsharma
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
Neeraj Kaushik
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
Rajesh Ananda Kumar
 
MultiThreading in Python
MultiThreading in PythonMultiThreading in Python
MultiThreading in Python
SRINIVAS KOLAPARTHI
 
advanced java programming paradigms presentation
advanced java programming paradigms presentationadvanced java programming paradigms presentation
advanced java programming paradigms presentation
PriyadharshiniG41
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Monika Mishra
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Raghu nath
 
Java multithreading
Java multithreadingJava multithreading
Java multithreading
Mohammed625
 
Multithreading
MultithreadingMultithreading
Multithreading
F K
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
ssuserfcae42
 
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
Hitendra 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.pptx
Arulmozhivarman8
 
Java Multithreading Interview Questions PDF By ScholarHat
Java Multithreading Interview Questions PDF By ScholarHatJava Multithreading Interview Questions PDF By ScholarHat
Java Multithreading Interview Questions PDF By ScholarHat
Scholarhat
 
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
Multithreading
sagsharma
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
Neeraj Kaushik
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
Rajesh Ananda Kumar
 
advanced java programming paradigms presentation
advanced java programming paradigms presentationadvanced java programming paradigms presentation
advanced java programming paradigms presentation
PriyadharshiniG41
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Monika Mishra
 
Ad

More from backdoor (20)

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

Recently uploaded (20)

Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 

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