1 / 10

Chapter 32 Multithreading

Chapter 32 Multithreading. Introduction. A program consists of multiple tasks Multithreading enables multiple tasks in a program to be executed concurrently Multithreading makes program more responsive , interactive and enhances the performance. Threads Concept.

keira
Télécharger la présentation

Chapter 32 Multithreading

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. Chapter 32 Multithreading

  2. Introduction • A program consists of multiple tasks • Multithreading enables multiple tasks in a program to be executed concurrently • Multithreading makes program more responsive, interactive and enhances the performance

  3. Threads Concept Multiple threads on multiple CPUs Multiple threads sharing a single CPU

  4. Creating Tasks and Threads

  5. Example:Using the Runnable Interface to Create and Launch Threads • Objective: Create and run three threads: • The first thread prints the letter a 100 times. • The second thread prints the letter b 100 times. • The third thread prints the integers 1 through 100. TaskThreadDemo Run

  6. The Thread Class

  7. Thread Pools Starting a new thread for each task could limit throughput and cause poor performance. A thread pool is ideal to manage the number of tasks executing concurrently. JDK 1.5 uses the Executor interface for executing tasks in a thread pool and the ExecutorService interface for managing and controlling tasks. ExecutorService is a subinterface of Executor.

  8. Creating Executors To create an Executor object, use the static methods in the Executors class. ExecutorDemo Run

  9. Another Example of Multithreading 1 of 2 public class TestThread { public static void main(String args[]) { RunnableDemo R1 = new RunnableDemo( "Thread-1"); RunnableDemo R2 = new RunnableDemo( "Thread-2"); // Create threads Thread thread1 = new Thread(R1); Thread thread2 = new Thread(R2); // Start threads thread1.start(); thread2.start(); } }

  10. Another Example of Multithreading 2 of 2 class RunnableDemo implements Runnable { private String threadName; RunnableDemo( String name){ threadName = name; System.out.println("Creating " + threadName ); } public void run() { System.out.println("Running " + threadName ); for(inti = 4; i > 0; i--) System.out.println("Thread: " + threadName + ", " + i); System.out.println("Thread " + threadName + " exiting."); } }

More Related