1 / 40

Introduction to Java Threads

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.

Lucy
Download Presentation

Introduction to Java Threads

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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.

  2. 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.

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

  4. A Multithreaded Program Main Thread start start start Thread A Thread B 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

  6. Multithreaded Server: For Serving Multiple Clients Concurrently Server Process Client 1 Process Server Threads • Internet Client 2 Process

  7. Modern Applications need Threads (ex1):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 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 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 1st time waiting for the CPU. Waiting: Sometimes, a thread transitions to the waiting state while the 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

  10. 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

  11. 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. • notifyAll(): 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 notifyAll() for this object

  12. 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 currentThread(). • General form: static Thread currentThread()

  13. In the program, a reference to the current thread is obtained by calling currentThread and reference is stored in local variable t. setName() 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 getName() obtains Threads name getPriority() obtains Threads priority join() wait for thread to terminate run() Entry point for the thread sleep() suspend a thread for a period of time start() show a thread by calling its run method. Program Example: Controlling the main Thread class CurrentThread { public static void main(String s[]) { Thread t=Thread.currentThread(); System.out.println("Current Thread:"+t); //Change name of the thread t.setName("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"); } } }

  14. 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

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

  16. 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, IllegalThreadStateException 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.

  17. An example class MyThread extends Thread { // the thread public void run() { System.out.println(" this thread is running ... "); } } // end class MyThread class ThreadEx1 { // a program that utilizes the thread public static void main(String [] args ) { MyThread t = new MyThread(); // 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 ThreadEx1

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

  19. Run 1 Run2 • [cse@lab1] threads [1:77] java ThreadTest From ThreadA: i= 1 From ThreadA: i= 2 From ThreadA: i= 3 From ThreadA: i= 4 From ThreadA: i= 5 From ThreadC: k= 1 From ThreadC: k= 2 From ThreadC: k= 3 From ThreadC: k= 4 From ThreadC: k= 5 Exit from C From ThreadB: j= 1 From ThreadB: j= 2 From ThreadB: j= 3 From ThreadB: j= 4 From ThreadB: j= 5 Exit from B Exit from A [cse@lab1] threads [1:76] java ThreadTest From ThreadA: i= 1 From ThreadA: i= 2 From ThreadA: i= 3 From ThreadA: i= 4 From ThreadA: i= 5 Exit from A From ThreadC: k= 1 From ThreadC: k= 2 From ThreadC: k= 3 From ThreadC: k= 4 From ThreadC: k= 5 Exit from C From ThreadB: j= 1 From ThreadB: j= 2 From ThreadB: j= 3 From ThreadB: j= 4 From ThreadB: j= 5 Exit from B

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

  21. 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.

  22. 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: • ThreadName.setPriority(intNumber) • MIN_PRIORITY = 1 • NORM_PRIORITY=5 • MAX_PRIORITY=10

  23. Thread Priority Example class A extends Thread { public void run() { System.out.println("Thread A started"); for(inti=1;i<=4;i++) { System.out.println("\t From ThreadA: i= "+i); } System.out.println("Exit from A"); }} class B extends Thread { public void run() { System.out.println("Thread B started"); for(int j=1;j<=4;j++) { System.out.println("\t From ThreadB: j= "+j); } System.out.println("Exit from B"); } } class C extends Thread { public void run() { System.out.println("Thread C started"); for(int k=1;k<=4;k++) { System.out.println("\t From ThreadC: k= "+k); } System.out.println("Exit from C"); }} class ThreadPriority { public static void main(String args[]) { A threadA=new A(); B threadB=new B(); C threadC=new C(); threadC.setPriority(Thread.MAX_PRIORITY); threadB.setPriority(threadA.getPriority()+1); threadA.setPriority(Thread.MIN_PRIORITY); System.out.println("Started Thread A"); threadA.start(); System.out.println("Started Thread B"); threadB.start(); System.out.println("Started Thread C"); threadC.start(); System.out.println("End of main thread"); }}

  24. 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. • Events 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.

  25. 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.

  26. 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.

  27. A Simple Applet

  28. An Example for Button Event

  29. Example of Event HandlingKeyboard Event

  30. Handling Mouse Events Program: import java.awt.event.*; import java.applet.*; /* <applet code=”MouseEvents” width=300 Height=100> </applet> */ public class MouseEvents extends Applet implements MouseListener,MouseMotionListener { String=” “; intmouseX=0,mousey=0; //Coordinates of mouse public void init() { addMouseListener(this); addMouseMotionListener(this); }

  31. //handle Mouse Entered public void mouseEntered(MouseEvent me) { //save coordinates mouseX=0; mousey=10; msg=”Mouse Entered”; repaint(); } //handle MouseExcited public void mouseExcited(MouseEvent me) { //save coordinates mouseX=0; mousey=10; msg=”Mouse Excited”; repaint(); }

  32. //handle Mouse Button pressed public void mousePressed(MouseEvent me) { //save coordinates mouseX=me.getX(); mousey=me.getY(); msg=”Down”; repaint(); } //handle Mouse Released public void mouseReleased(MouseEvent me) { //save coordinates mouseX=me.getX(); mousey=me.getY(); msg=”Up”; repaint(); }

  33. //handle Mouse Dragged public void mouseDragged(MouseEvent me) { //save coordinates mouseX=me.getX(); mousey=me.getY(); msg=”*”; showStatus(“Dragging mouse at “+mouseX+” “mousey); repaint(); } //handle Mouse moved public void mouseMoved(MouseEvent me) { showStatus(“Moving mouse at “+me.getX()+”, “+me.getY()); } //Display message in applet window at current x, y location public void paint(Graphics g) { g.drawString(msg,mouseX,mousey); } }

  34. Exercises • Write a program to create two threads t1,t2 which should prints odd numbers, and even numbers respectively and stops thread after creating 3 odd numbers. • Write a program TestThreadMany.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.

More Related