Docsity

Threads-Java Programming-Lecture Slides, Slides of Java Programming

Partial preview of the text

Download Threads-Java Programming-Lecture Slides and more Slides Java Programming in PDF only on Docsity!

ava - programming

An Introduction

Threads

J

©Nauman Shamim@DCIS-PIEAS

Islamabad-Pakistan

Assignment

  • Write an applet that looks like the

figure given, the applet should

behave as follows

  • Transfer Text button should

display the text entered in text

field on the Text Board

  • Change Font should change the

font of the text on the TextBoard

as selected from the choice list

  • Change color should change

either the color the text on

TextBoard or background of the

TextBoard

  • Change Style should change the

style of the text on the TextBoard

according to the selection

Threads and Multi Threading

  • Thread and processes

 Light weight process

 Each program has one or more threads or process

 Each process required some time slice from the processor

 The time slice is different on different machines and termed as quantum

 The value of quantum lies somewhere in milliseconds

  • Single Thread Program

 Based on a single thread

 Instructions in the program executes turn by turn

 Concurrent processing is not possible

 Example

 Programs written in C\C++ [Some plat from support multi threaded program using system specific code libraries]

 Not suitable for each type of application

 Example  Animations in web browser  Operating system

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 classes

  • Package

 java.lang.

  • Classes

 java.lang.Thread

 Thread [class]

 For creating threads directly

 For creating threads through child classes

 ThreadGroup

 ThreadLocal

 ThreadDeath

  • An important interface

 Runnable

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 Life Cycle

  • Thread states

 Born

 When the thread object is created by not executed yet  The thread is not doing any thing in this state

 Ready

 When start method is called  Thread is waiting for its turn to execute

 Running

 when the system assigns resources to the thread  The thread’s run method is now executing its code

 Dead

 When the run method is completed or exception is raised  A thread is disposed after it is dead

 Blocked

 When the thread is issues some I/O request  The thread comes back to ready state when I/O operation is completed

 Sleep

 A suspended state , the thread is not doing anything

 Wait

 A wait state , becomes when notified

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

MyThread explained

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"); try{ t1.start();

t2.start();

t3.start();

t4.start();

Thread.sleep(3000); }catch(Exception e){e.printStackTrace();} System.out.println(“End main”);

} //end main } //end of class MyThread

run( ){ While(true){ System.out.println(“Thread = “+name); Thread.sleep(1000);} }

run( ){ While(true){ System.out.println(“Thread = “+name); Thread.sleep(1000);} }

run( ){ While(true){ System.out.println(“Thread = “+name); Thread.sleep(1000);} }

run( ){ While(true){ System.out.println(“Thread = “+name); Thread.sleep(1000);} }

Thread

Thread1: Thred

Thread Thread Thread Thread4:

Thread Thread Thread

Thread Thread Thread Thread End main:

End main Thread Thread Thread Thread

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

Wait sleep notify and notifiyAll

  • wait( )

 Cause the invoker thread to wait

 In wait state the thread does not contend for processor

 Even lower priority thread in the queue can proceed

 Overridden method

 Wait( )

 Will wait for ever unless notified by some thread  The thread becomes ready when notified  Executes its code when processor is assigned to it

 Wait( int millisecond)

 Wait for a defined amount of time and then becomes ready

  • Sleep( )

 Cause a thread to sleep

 Works like wait( ) but cannot be notified

 A sleeping thread can be interrupted

 Overridden method

 sleep(int millisecond )

 Cause the thread to sleep for specified amount time

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

A producer consumer program

  • Producer class

 A thread

 Produces some values

  • Consumer class

 A thread

 Consumes the values generated

  • A shared object

 Not a thread

 Shared class

 An object whose methods are called by producer and consumers

  • Un-Synchronized attempt

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