Java Threads Introduction to Java Threads Thread is

  • Slides: 40
Download presentation
Java Threads

Java Threads

Introduction to Java Threads � � � � Thread is a lightweight components and

Introduction to Java Threads � � � � Thread is a lightweight components and it is a flow of control. It is a part of process or a Single path of execution Threads share the same address space and therefore can share both data and code Threads allow different tasks to be performed concurrently. Multithreading in java is a process of executing multiple threads simultaneously. The aim of multithreading is to achieve the concurrent execution. But we use multithreading than multiprocessing because threads share a common memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process. Java Multithreading is mostly used in games, animation etc.

Introduction to Multithreading � Multitasking means when multiple processes share common processing resources such

Introduction to Multithreading � Multitasking means when multiple processes share common processing resources such as a CPU. Process-based Multitasking(Multiprocessing) � Thread-based Multitasking(Multithreading) � � Process-based Multitasking (Multiprocessing) Each process have its own address in memory i. e. each process allocates separate memory area. � Process is heavyweight. � Cost of communication between the process is high. � Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc. � � Thread-based Multitasking (Multithreading) Threads share the same address space. � Thread is lightweight. � Cost of communication between the thread is low. �

A single threaded program class ABC { …. public void main(. . ) {

A single threaded program class ABC { …. public void main(. . ) { …. . } } 4 begin body end

A Multithreaded Program Main Thread start Thread A start Thread B start Thread C

A Multithreaded Program Main Thread start Thread A start Thread B start Thread C Threads may switch or exchange data/results 5

Web/Internet Applications: Serving Many Users Simultaneously PC client Internet Server Local Area Network PDA

Web/Internet Applications: Serving Many Users Simultaneously PC client Internet Server Local Area Network PDA 6

Multithreaded Server: For Serving Multiple Clients Concurrently Server Process Client 1 Process Server Threads

Multithreaded Server: For Serving Multiple Clients Concurrently Server Process Client 1 Process Server Threads n Client 2 Process 7 Internet

Modern Applications need Threads (ex 1): Editing and Printing documents in background. Printing Thread

Modern Applications need Threads (ex 1): Editing and Printing documents in background. Printing Thread Editing Thread 8

Single and Multithreaded Processes threads are light-weight processes within a process Single-threaded Process Multiplethreaded

Single and Multithreaded Processes threads are light-weight processes within a process Single-threaded Process Multiplethreaded Process Threads of Execution Multiple instruction stream Single instruction stream Common Address Space 9

State or Life cycle of thread New State If any new thread class is

State or Life cycle of thread New State If any new thread class is created that represent new state of a thread, In new state thread is created and about to enter into main memory. No memory is available if the thread is in new state. Ready State In ready state thread will be entered into main memory, memory space is allocated for the thread and 1 st time waiting for the CPU. Waiting: Sometimes, a thread transitions to the waiting state while thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing. Running State Whenever the thread is under execution known as running state. Halted or dead State If the thread execution is stoped permanently than it comes under dead state, no memory is available for the thread if its comes to dead state

Multithreading in Java � � Multi threading extends the idea of multitasking into applications

Multithreading in Java � � Multi threading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application. The Java Virtual machine has its own runtime threads In java language multithreading can be achieve in two different ways. Using thread class � Using Runnable interface �

Thread Methods � � � � Extending Thread Class is required to 'override run()'

Thread Methods � � � � Extending Thread Class is required to 'override run()' method. The run method contains the actual logic to be executed by thread. Creation of thread object never starts execution, we need to call 'start()' method to run a thread. join(): It makes to wait for this thread to die. You can wait for a thread to finish by calling its join() method. sleep(): It makes current executing thread to sleep for a specified interval of time. Time is in milli seconds. yield(): It makes current executing thread object to pause temporarily and gives control to other thread to execute. notify(): This method is inherited from Object class. This method wakes up a single thread that is waiting on this object's monitor to acquire lock. notify. All(): This method is inherited from Object class. This method wakes up all threads that are waiting on this object's monitor to acquire lock. wait(): This method is inherited from Object class. This method makes current thread to wait until another thread invokes the notify() or the notify. All() for this object

The Main Thread � When JAVA program starts, one thread begins running immediately which

The Main Thread � When JAVA program starts, one thread begins running immediately which is called as main thread. � Main thread is important for two reasons � It is the thread from which other child threads will be spawned. � It must be the last thread to finish execution. � Although main thread is created automatically, we can control through a Thread Object, to do so you reference by calling method current. Thread(). � General form: static Thread current. Thread()

Program Example: Controlling the main Thread class Current. Thread { public static void main(String

Program Example: Controlling the main Thread class Current. Thread { public static void main(String s[]) { Thread t=Thread. current. Thread(); System. out. println("Current Thread: "+t); //Change name of the thread t. set. Name("My thread"); System. out. println("After name change: "+t); try { for(int n=5; n>0; n--) { System. out. println(n); Thread. sleep(1000); } } catch(Exception e) { System. out. println("Exception"); } } } In the program, a reference to the current thread is obtained by calling current. Thread and reference is stored in local variable t. set. Name() to change name of thread. Following with loop, continue to count for five and displays it. In the output you will see [name of thread, its priority and name of its group] Here 1. get. Name() obtains Threads name 2. get. Priority() obtains Threads priority 3. join() wait for thread to terminate 4. run() Entry point for the thread 5. sleep() suspend a thread for a period of time 6. start() show a thread by calling its run method.

Java Thread By Implementing Runnable Interface � � A Thread can be created by

Java Thread By Implementing Runnable Interface � � A Thread can be created by extending Thread class also. But Java allows only one class to extend, it won’t allow multiple inheritance. So it is always better to create a thread by implementing Runnable interface. Java allows you to impliment multiple interfaces at a time. By implementing Runnable interface, you need to provide implementation for run() method. To run this implementation class, create a Thread object, pass Runnable implementation class object to its constructor. Call start() method on thread class to start executing run() method. Implementing Runnable interface does not create a Thread object, it only defines an entry point for threads in your object. It allows you to pass the object to the Thread(Runnable implementation) constructor

An example class My. Thread implements Runnable { public void run() { System. out.

An example class My. Thread implements Runnable { public void run() { System. out. println(" this thread is running. . . "); } } // end class My. Thread class Thread. Ex 2 { public static void main(String [] args ) { Thread t = new Thread(new My. Thread()); // due to implementing the Runnable interface // I can call start(), and this will call run(). t. start(); } // end main() } // end class Thread. Ex 2 16

Java Thread By Extending Thread Class A thread can be created in java by

Java Thread By Extending Thread Class A thread can be created in java by extending Thread class, where you must override run() method. � Call start() method to start executing the thread object. � Can we Start a thread twice ? � No, a thread cannot be started twice. If you try to do so, Illegal. Thread. State. Exception will be thrown. � When a thread is in running state, and you try to start it again, or any method try to invoke that thread again using start() method, exception is thrown. �

An example class My. Thread extends Thread { // the thread public void run()

An example class My. Thread extends Thread { // the thread public void run() { System. out. println(" this thread is running. . . "); } } // end class My. Thread class Thread. Ex 1 { // a program that utilizes the thread public static void main(String [] args ) { My. Thread t = new My. Thread(); // due to extending the Thread class (above) // I can call start(), and this will call // run(). start() is a method in class Thread. t. start(); } // end main() } // end class Thread. Ex 1

A Program with Three Threads class A extends Thread { public void run() {

A Program with Three Threads class A extends Thread { public void run() { for(int i=1; i<=5; i++) { System. out. println("t From Thread. A: i= "+i); } System. out. println("Exit from A"); } } } class B extends Thread { public void run() { class Thread. Test { public static void main(String args[]) for(int j=1; j<=5; j++) { System. out. println("t From Thread. B: j= "+j); } System. out. println("Exit from B"); } 19 class C extends Thread { public void run() { for(int k=1; k<=5; k++) { System. out. println("t From Thread. C: k= "+k); } System. out. println("Exit from C"); }} { } } new A(). start(); new B(). start(); new C(). start();

Run 1 [cse@lab 1] threads [1: 76] java Thread. Test From Thread. A: i=

Run 1 [cse@lab 1] threads [1: 76] java Thread. Test From Thread. A: i= 1 From Thread. A: i= 2 From Thread. A: i= 3 From Thread. A: i= 4 From Thread. A: i= 5 Exit from A From Thread. C: k= 1 From Thread. C: k= 2 From Thread. C: k= 3 From Thread. C: k= 4 From Thread. C: k= 5 Exit from C From Thread. B: j= 1 From Thread. B: j= 2 From Thread. B: j= 3 From Thread. B: j= 4 From Thread. B: j= 5 Exit from B Run 2 [cse@lab 1] threads [1: 77] java Thread. Test From Thread. A: i= 1 From Thread. A: i= 2 From Thread. A: i= 3 From Thread. A: i= 4 From Thread. A: i= 5 From Thread. C: k= 1 From Thread. C: k= 2 From Thread. C: k= 3 From Thread. C: k= 4 From Thread. C: k= 5 Exit from C From Thread. B: j= 1 From Thread. B: j= 2 From Thread. B: j= 3 From Thread. B: j= 4 From Thread. B: j= 5 Exit from B Exit from A

� is. Alive() and join() � How will a one thread know whether another

� is. Alive() and join() � How will a one thread know whether another thread has ended or not? � is. Alive() and join() are two different methods to check whether a thread has finished its execution. � Call is. Alive() General form: final Boolean is. Alive() Returns true if thread is still running or false otherwise. � join() � General form: final void join() throws Interrupted. Exception Method waits until the thread on which it is called terminates. Name tells you calling thread waits until specified thread joins it.

Using join() method, we tell our thread to wait until the specified thread completes

Using join() method, we tell our thread to wait until the specified thread completes its execution. There are overloaded versions of join() method, which allows us to specify time for which you want to wait for the specified thread to terminate.

Thread Priority � In Java, each thread is assigned priority, which affects the order

Thread Priority � In Java, each thread is assigned priority, which affects the order in which it is scheduled for running. The threads so far had same default priority (ORM_PRIORITY) and they are served using FCFS policy. � Java allows users to change priority: Thread. Name. set. Priority(int. Number) �MIN_PRIORITY = 1 �NORM_PRIORITY=5 �MAX_PRIORITY=10 24

Thread Priority Example class A extends Thread { public void run() { System. out.

Thread Priority Example class A extends Thread { public void run() { System. out. println("Thread A started"); for(int i=1; i<=4; i++) { System. out. println("t From Thread. A: i= "+i); } System. out. println("Exit from A"); }} class B extends Thread { public void run() { System. out. println("Thread B started"); { System. out. println("t From Thread. C: k= "+k); } System. out. println("Exit from C"); }} class Thread. Priority { public static void main(String args[]) { A thread. A=new A(); B thread. B=new B(); C thread. C=new C(); thread. C. set. Priority(Thread. MAX_PRIORITY) ; thread. B. set. Priority(thread. A. get. Priority()+1); thread. A. set. Priority(Thread. MIN_PRIORITY); System. out. println("Started Thread A"); thread. A. start(); for(int j=1; j<=4; j++) System. out. println("Started Thread B"); { System. out. println("t From Thread. B: j= "+j); thread. B. start(); } System. out. println("Started Thread C"); thread. C. start(); System. out. println("Exit from B"); } System. out. println("End of main thread"); } }} class C extends Thread { public void run() { System. out. println("Thread C started"); for(int k=1; k<=4; k++)

Event handling in java

Event handling in java

Event and Listener � � � Changing the state of an object is known

Event and Listener � � � Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The java. awt. event package provides many event classes and Listener interfaces for event handling. Any program that uses GUI (graphical user interface) such as Java application written for windows, is event driven. Event handling has three main components, � Events : An event is a change of state of an object. Source : Event source is an object that generates an event. � Listeners : A listener is an object that listens to the event. A listener gets notified when an event occurs.

� � Ø If we want to provide action to the components present in

� � Ø If we want to provide action to the components present in java. awt package we need to handle events generated by component. To use Event handling mechanism we need to import java. awt. event. * package. Delegation event model: � It has two parts: Sources & Listeners � Here Source generates an event & sends it to one or more listeners. � The Listener simply waits until it receives an event. � Once it is obtained it processes this event and returns. � Listeners should register themselves with a source in order to receive an event notification. � Notifications are sent only to listeners that want to receive them.

Applet in Java � � Applets are small Java applications that can be accessed

Applet in Java � � Applets are small Java applications that can be accessed on an Internet server, transported over Internet, and can be automatically installed and run as apart of a web document. Any applet in Java is a class that extends the java. applet. Applet class. An Applet class does not have any main() method. It is viewed using JVM. The JVM can use either a plug-in of the Web browser or a separate runtime environment to run an applet application. JVM creates an instance of the applet class and invokes init() method to initialize an Applet.

A Simple Applet

A Simple Applet

An Example for Button Event

An Example for Button Event

Example of Event Handling Keyboard Event

Example of Event Handling Keyboard Event

Handling Mouse Events Program: import java. awt. event. *; import java. applet. *; /*

Handling Mouse Events Program: import java. awt. event. *; import java. applet. *; /* <applet code=”Mouse. Events” width=300 Height=100> </applet> */ public class Mouse. Events extends Applet implements Mouse. Listener, Mouse. Motion. Listener { String=” “; int mouse. X=0, mousey=0; //Coordinates of mouse public void init() { add. Mouse. Listener(this); add. Mouse. Motion. Listener(this); }

//handle Mouse Entered public void mouse. Entered(Mouse. Event me) { //save coordinates mouse. X=0;

//handle Mouse Entered public void mouse. Entered(Mouse. Event me) { //save coordinates mouse. X=0; mousey=10; msg=”Mouse Entered”; repaint(); } //handle Mouse. Excited public void mouse. Excited(Mouse. Event me) { //save coordinates mouse. X=0; mousey=10; msg=”Mouse Excited”; repaint(); }

//handle Mouse Button pressed public void mouse. Pressed(Mouse. Event me) { //save coordinates mouse.

//handle Mouse Button pressed public void mouse. Pressed(Mouse. Event me) { //save coordinates mouse. X=me. get. X(); mousey=me. get. Y(); msg=”Down”; repaint(); } //handle Mouse Released public void mouse. Released(Mouse. Event me) { //save coordinates mouse. X=me. get. X(); mousey=me. get. Y(); msg=”Up”; repaint(); }

//handle Mouse Dragged public void mouse. Dragged(Mouse. Event me) { //save coordinates mouse. X=me.

//handle Mouse Dragged public void mouse. Dragged(Mouse. Event me) { //save coordinates mouse. X=me. get. X(); mousey=me. get. Y(); msg=”*”; show. Status(“Dragging mouse at “+mouse. X+” “mousey); repaint(); } //handle Mouse moved public void mouse. Moved(Mouse. Event me) { show. Status(“Moving mouse at “+me. get. X()+”, “+me. get. Y()); } //Display message in applet window at current x, y location public void paint(Graphics g) { g. draw. String(msg, mouse. X, mousey); } }

Exercises 1. 2. 3. Write a program to create two threads t 1, t

Exercises 1. 2. 3. Write a program to create two threads t 1, t 2 which should prints odd numbers, and even numbers respectively and stops thread after creating 3 odd numbers. Write a program Test. Thread. Many. java that takes a positive integer n from the command line and creates exactly n threads that print out their own name Write a multithreaded program to implement y=sinx+cosx+tanx ((Note: Convert Degree to Radian.