Docsity

Java Multi-Threading: Understanding Threads, Thread Life Cycle, and Synchronization, Slides of Java Programming

Partial preview of the text

Download Java Multi-Threading: Understanding Threads, Thread Life Cycle, and Synchronization and more Slides Java Programming in PDF only on Docsity!

ava - programming

An

Introduction

Java Short Course

Day-

J

Outline

  • Threads
  • What, Why
  • Thread life cycle
  • The Thread class
  • Important Methods
  • Creating Threads
  • The Runnable Interface
  • A Multi Thread Program
  • Project or Exam

Threads and multi threading..

  • Multi-Threaded Programs

 More than one execution threads

 Each thread can execute independently

 Example

 An audio clip downloading program  One thread to download  One thread to execute the downloaded code

 Java’s garbage collector  One thread executes program  One thread keep tracks of orphans

 Document printing software  One thread renders the documents  One thread starts printing the rendered documents  One thread queues other jobs arriving mean while

 Complexity of Multi-Thread programs

 Threads co-ordination with each other  In case of audio clip downloading program the thread playing the audio clip should co-ordinate with downloading thread

 Difficult to keep track the execution of code while programming

 Threads synchronization

Multi-Threading in Java

  • Platform issues

 Different Implementations as different thread architecture supported by the

platform

 Solaris Implementation

 Win32 Implementation (for Windows 95 and Windows NT)

  • Solaris Java platform

 A threads completes its execution

 Preemption

 Only by a higher priority thread, i.e. the processor is given to the higher priority thread  The low priority thread (which is preempted) must have to wait

  • Wind32 Java platform

 Threads are time sliced

 Each thread is given a small amount of time on processor  Other threads wait for their turn

 Pre-emption

 Higher priority thread  By an equal priority thread

The Thread class

  • Constructor

 Thread(String name)

 Creates a thread whose name is specified with “name” variable

 Thread()

 Creates a thread whose name is “Thread-” concatenated with a number e.g. Thread-1,Thread-

  • Important methods

 run()

 The heart of a thread

 When a thread execute the code in run( ) method executes independently

 start( )

 Used by the caller program

 Calls the run method and returns to the caller program

 The launched thread executes independently

 Sleep( )

 Static method

 Can cause a thread to sleep for defined number of milliseconds

 A sleeping thread does nt contend for processor

thread class..cont..

 isAlive( )

 Used to get the status of a thread whether it is dead or executing

 setName()

 To assign a name to a thread

 getName( )

 To query the name of a thread

 currentThread( )

 Static method

 Can be called to get a reference to the currently executing thread

 join( )

 Use to join other threads

 Waits for the other thread to die before joining thread can proceed

 The wait time can be defined and it is recommended to be defined

Creating Threads

  • Each child of Thread class is a thread

 Extend the Thread class  Override the run( ) methods

  • Example

public class MyThread extends Thread{

String name; public MyThread(){ }

public MyThread(String name){ this.name=name; }

public void run(){ try{ while(true){ Thread.sleep(2000); System.out.println("Thread + name ); } }catch(Exception e ) { e.printStackTrace(); } }

public static void main(String s[]){ MyThread t1=new MyThread("Thread1"); MyThread t2=new MyThread("Thread2"); MyThread t3=new MyThread("Thread3"); MyThread t4=new MyThread("Thread4"); t1.start(); t2.start(); t3.start(); t4.start(); System.out.println(“End main”);

} //end main

} //end of class MyThread

public class MyThread extends Thread{

MyThread Expalined

String name;

public MyThread(){ }

public MyThread(String name){

this.name=name;

public void run(){

try{

while(true){

Thread.sleep(1000);

System.out.println("Thread” + name );

}catch(Exception e ) { e.printStackTrace(); }

Threads Priorities

  • Every java thread has a priority
  • Priority ranges

 Thread.MIN_PRIORITY  A constant 1  Thread.MAX_PRIORITY  A constant 10

  • Default Priotiry

 Thread.NOMR_PRIORITY  A constant 5

  • Priority of equal threads

 On non-time sliced system  Equal level threads execute turn by turn unless completed  On-time sliced system  Equal level threads executes only for a quantum either completed or not

  • Higher priority threads

 Preemption can occur  If a lower and a higher priority thread contend for processor higher priority thread will be given preference over lower priority thread  Indefinite postponment  A lower priority thread can fall to indefinite postponement by a higher priority thread  Java Scheduler  Controls, schedule and keep track of thread priority

  • Knowing the priority of a thread

 int getPriority()

 Returns the priority of the current thread whose method is called

  • Changing a Thread’s priority

 setPriority(int p)

 IllegalArgumentException

 Caused if a number is out of priority range

Wait,sleep,notify

  • notify( )

 Used for threads in wait state

 After notified the threads become ready

  • notifyAll( )

 Notify all thread in wait state

 The threads will become ready and execute according to their priorites

  • interrupt

 Used to interrupt a sleeping thread

 The sleeping thread becomes ready after interruption

Thread Synchronization

  • Many threads one shared object

 Example

 An ATM machine operation  Only one machines is allowed to access the account balance of a user after which other machines can perform operations on that account

 Synchronization

 When two or more threads use such a shared object the sharing must be synchronized

 No synchronization! object state?

  • Java monitors

 Used for synchronizing shared objects

 A monitor only one thread to use a shared object

 The shared object is locked for the duration of operations by a thread

 Keyword “ synchronized ”

 Used to declare a shared object as synchronized

 Any method that is to be called by more than one thread must be declared

synchronized

 Several Synchronized methods

 Only one will execute at a time

 Other threads

 Fall in a wait state that exits when notified

Producer class

public class Producer extends Thread{

private Shared sharedObj;

public Producer(Shared shobj){

sharedObject=shobj;

public void run( ) {

try{ While(true){ int num; num=(int)Math.random()2000; sharedObj.setInt(num); Systme.out.println(“number produced “+num); Thread.sleep((int)Math.random()1000; } }catch(Exception e){e.printStackTrace();}

} //end of run

} //end class producer

Consumer class

public class Consumer extends Thread{

private Shared sharedObj;

public Consumer(Shared shobj){

sharedObject=shobj;

public void run( ) {

try{

While(true){

int num;

Num=sharedObj.getInt(num);

Systme.out.println(“Number consumed “+num);

Thread.sleep((int)Math.random()*1000;

}

}catch(Exception e){e.printStackTrace();}

} //end of run

} //end class producer