Java Threads and Multithreading

Java Threads and Multithreading
Slide Note
Embed
Share

Multitasking and Multithreading in Java refer to the ability of a computer to perform multiple jobs concurrently. Multithreading involves multiple threads of control within a single program, enhancing performance and reducing computation time. Learn about the advantages of multithreading, applications, and threading mechanisms such as extending the Thread class or implementing the Runnable interface. Discover how threads and processes interact, the difference between concurrency and parallelism, and explore scenarios like serving users simultaneously in web/internet applications.

  • Java Threads
  • Multithreading
  • Concurrency
  • Parallelism
  • Advantages

Uploaded on Mar 03, 2025 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Java Threads

  2. Multitasking and Multithreading Multitasking: refers to a computer's ability to perform multiple jobs concurrently more than one program are running concurrently, e.g., UNIX Multithreading: A thread is a single sequence of execution within a program. Multithreading refers to multiple threads of control within a single program each program can run multiple threads of control within it, e.g., Web Browser

  3. Concurrency vs. Parallelism CPU CPU1 CPU2

  4. Threads and Processes CPU main run Process 1 Process 2 Process 3 Process 4 GC

  5. Advantages of multithreading 1. Reduces the computation time. 2. Improves performance of an application. 3. Threads distribute the same address space so it saves the memory. 4. Context switching between threads is usually less costly than between processes. 5. Cost of communication between threads is comparatively low.

  6. Applications When we execute an application: The JVM creates a Thread object whose task is defined by the main() method The JVM starts the thread The thread executes the statements of the program one by one After executing all the statements, the method returns and the thread dies

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

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

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

  10. Threading Mechanisms... Create a class that extends the Thread class Create a class that implements the Runnable interface In both cases the run() method should be implemented 10

  11. 1st method: Extending Thread class Threads are implemented as objects that contains a method called run() class MyThread extends Thread { public void run() { // thread body of execution } } Create a thread: MyThread thr1 = new MyThread(); Start Execution of threads: thr1.start();

  12. class MyThread extends Thread { public void run() { System.out.println(" this thread is running ... "); } } class ThreadEx1 { public static void main(String [] args ) { MyThread t = new MyThread(); t.start(); } }

  13. 2nd method: Threads by implementing Runnable interface class MyThread implements Runnable { public void run() { // thread body of execution } } Creating Object: MyThread myObject = new MyThread(); Creating Thread Object: Thread thr1 = new Thread( myObject ); Start Execution: thr1.start();

  14. A Runnable Object When running the Runnable object, a Thread object is created from the Runnable object The Thread object s run() method calls the Runnable object s run() method Allows threads to run inside any object, regardless of inheritance

  15. An example class MyThread implements Runnable { public void run() { System.out.println(" this thread is running ... "); } } class ThreadEx2 { public static void main(String [] args ) { Thread t = new Thread(new MyThread()); t.start(); } }

  16. A Program with Three Java Threads Write a program that creates 3 threads class A extends Thread { public void run() { for(int i=1;i<=5;i++) { System.out.println("\t From ThreadA: i= "+i); } System.out.println("Exit from A"); } }

  17. class B extends Thread { public void run() { for(int i=1;i<=5;i++) { System.out.println("\t From ThreadB: i= "+i); } System.out.println("Exit from B"); } }

  18. class C extends Thread { public void run() { for(int i=1;i<=5;i++) { System.out.println("\t From ThreadC: i= "+i); } System.out.println("Exit from C"); } }

  19. class ThreadTest { public static void main(String args[]) { new A().start(); new B().start(); new C().start(); } }

  20. Thread Methods void start() Creates a new thread and makes it runnable This method can be called only once. aThread.start() void run() The new thread begins its life inside this method

  21. Stopping a Thread Whenever we want to stop a thread from running further, call stop() method aThread.stop() This method causes the thread to move to dead state. The stop may used when the premature death of thread is desired.

  22. Blocking a Thread A thread can also be temporarily suspended or blocked from entering into the runnable and running state by using following methods. sleep() :blocked for specified time suspend() :blocked until further orders ( resume() ) wait() :blocked until certain conditions occurs (notify()) These methods causes the thread to go into blocked state.

  23. Thread Methods void yield() Causes the currently executing thread object to temporarily pause and allow other threads to execute. Allow only threads of the same priority to run. void sleep(int m) or sleep(int m, int n) The thread sleeps for m milliseconds, plus n nanoseconds.

  24. Life Cycle of Thread During Life time of a thread there are many states it can enter. Newborn state Runnable state Running state Blocked state Dead state A thread is always in one of these five states. It can move from one state to another via a variety of ways.

  25. Thread State Diagram Newborn Thread new ThreadExample(); stop() thread.start(); Active Thread run() method returns Runnable Running Running Dead Thread yield wait() sleep() Suspend() resume() notify() stop() Blocked Idle Thread Not Runnable

  26. Newborn State When we create a thread object, the thread is born and is said to be in newborn state. The thread is not yet scheduled for running. At this state we can do only the following things Newborn stop(); start(); Dead Thread Runnable

  27. Runnable State Means that thread is ready for execution and is waiting for the availability of the processor. That is , thread has joined the waiting queue. Threads with equal priority are scheduled in round robin fashion. i.e. (FCFS) However, a thread can relinquish control to another thread by using yield() method. yield() Runnable Threads Running Thread

  28. Running State Running means that processor has given its time to the thread for its execution. The thread runs until it relinquishes control on its own or it is interrupted by higher priority thread. The running thread may relinquish its control in one of the following situations. It has been suspended using suspend() method. It has been made to sleep It has been told to wait until some event occurs.

  29. It has been suspended using suspend() method. suspend() resume() Running Runnable Suspended 2. It has been made to sleep sleep(t) after(t) Running Suspended Runnable 3. It has been told to wait until some event occurs wait notify Waiting Runnable Running

  30. Blocked State A thread is blocked when it is prevented from entering into the runnable and running state. This happens when thread is suspended, sleeping, or waiting in order to satisfy certain requirements. A blocked thread is not runnable but not dead and therefor fully qualified to run again. Dead State Every thread has life cycle. A thread ends its life when it has completed its execution. It is natural death. However we can kill it by sending the stop message. A thread can be killed as soon as it born. Demo ThreadMethods

  31. Scheduling Threads start() Ready queue Newly created threads Currently executed thread I/O operation completes Waiting for I/O operation to be completed Waiting to be notified Sleeping Waiting to enter a synchronized section

  32. Preemptive Scheduling Preemptive scheduling the thread scheduler preempts (pauses) a running thread to allow different threads to execute. Nonpreemptive scheduling the scheduler never interrupts a running thread.

  33. Thread Priority Every thread has a priority. When a thread is created, it inherits the priority of the thread that created it. The priority values range from 1 to 10, in increasing priority.

  34. Thread Priority (cont.) The priority can be adjusted subsequently using the setPriority() method Threadname.setPriority(intNumber); The priority of a thread may be obtained using getPriority() Priority constants are defined: MIN_PRIORITY=1 MAX_PRIORITY=10 The main thread is created with priority NORM_PRIORITY NORM_PRIORITY=5

  35. Synchronization In Java, the threads are executed separately to each other. These threads are called as asynchronous. But what if two threads try to use same data? For example, one thread may try to read record from a file while another is still writing to same file. Depending on the situation we may get strange results.

  36. Synchronization Java enables us to overcome this using synchronization. Keyword synchronized helps to solve such problems. The method that will read the file and method that will update file may be declared as synchronized. synchronized void update() { . }

  37. Synchronization Java creates a monitor and hands it to the thread that calls the method first time. As long as the method holds the monitor, no other thread can enter the synchronized section of code. A monitor is like a key and the thread is that holds the key can only open the lock. Whenever a thread has completed its work it will handover the monitor the next thread. Demo SynThread1.java

Related


More Related Content