100 likes | 265 Views
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.
E N D
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 Multiple threads on multiple CPUs Multiple threads sharing a single CPU
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
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.
Creating Executors To create an Executor object, use the static methods in the Executors class. ExecutorDemo Run
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(); } }
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."); } }