Java Multithreading (CSCI 2308) - Programming 3 PDF

Document Details

WellMadeSerpentine1417

Uploaded by WellMadeSerpentine1417

Islamic University of Gaza

2025

Dr. Abdelkareem Alashqar

Tags

java multithreading programming computer science threads

Summary

This document is a lecture presentation on Java multithreading, explaining concurrency and parallelism concepts within the context of a programming course. It details different thread states, thread properties, and techniques for synchronization. The document was created on January 18, 2025.

Full Transcript

Programming 3 CSCI 2308 Chapter 7 Java Multithreading Topics Covered  Introduction  Concurrency vs Parallelism  What is a Thread?  Threads and Processes  Thread Properties  Thread States  Thread & Runnable  Synchronization  Threads...

Programming 3 CSCI 2308 Chapter 7 Java Multithreading Topics Covered  Introduction  Concurrency vs Parallelism  What is a Thread?  Threads and Processes  Thread Properties  Thread States  Thread & Runnable  Synchronization  Threads Pool & Executers  Callable Interface Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 2 Introduction  Multitasking: Multitasking refers to a computer's ability to perform multiple jobs concurrently ‫نفس الوقت‬ ̶More than one program are running concurrently on the same machine  Multitasking is divided into two types: Process-based: in which two or more programs runs concurrently. ̶For example user can run Windows Calculator and Notepad at the same time. Thread-based: A single program can perform two or more tasks simultaneously.‫معا‬ ̶For example MS Word can print while formatting is being done. Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 3 Concurrency vs Parallelism Concurrency Parallelism Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 4 What is a Thread?  A thread is a basic processing unit to which an operating system allocates ‫يخصص‬processor time, and more than one thread (multithreading) can be executing code inside a process.  Multithreading enables programmer to write a very efficient programs that make maximum use of CPU, because idle time ‫ وقت الخمول‬can be kept to minimum. This is especially important for the interactive networked application because idle time is common. Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 5 Threads and Processes Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 6 Thread Properties  Every Java program has at least one thread, the thread that executes the Java program. It is created when main method has been invoked in the desired Java class.  Thread properties: A thread can be run ̶ It can be ready to run as soon as it begins execution. A running thread can be suspended (pause) which temporarily suspends its activity and it can be resumed. A thread can be blocked when waiting for a resource. ̶ Sleeps for a while At any time a thread can be terminated, which means the thread stops. ̶ Once stopped it cannot be resumed. Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 7 Thread States  Every Thread has a state and a Thread can be in one of the following: New: A state in which a thread has NOT been started. Runnable: A state in which a thread is executing. Blocked: A state in which a thread is waiting for a lock to access an object. Waiting: A state in which a thread is waiting indefinitely ‫اجل‬ ‫ غير مسمى‬for another thread to perform an action. Timed_waiting: A state in which a thread is waiting for up to a specified period of time for another thread to perform an action. Terminated: A state in which a thread has exited. Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 8 Thread States Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 9 Creating Thread  There are two ways to create our own Thread object: Sub-classing the Thread class and instantiating a new object of that class. ̶ This means extends the java.lang.Thread class Implementing the Runnable interface ̶ This means implements the java.lang.Runnable interface  In both cases the run() method must be implemented.  Since multiple inheritance doesn't allow us to extend more than one class at a time, implementing the Runnable interface may help us in this situation. Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 10 Creating Thread  Once Thread object has been created, its start method can be called to start the thread.  When a thread is started, its run method is executed.  Once the run method returns or throws an exception, the thread dies and will be garbage- collected. Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 11 Thread & Runnable public class MyThread extends Thread { private int sleep; @Override public void run() { try { super.run(); for (int i = 0; i < 100; i++) { System.out.println(this.getName() +" "+i); Thread.sleep(sleep); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public MyThread(int sleep) { super(); this.sleep = sleep; } } Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 12 Thread & Runnable public class MyRunnable implements Runnable { private int sleep; @Override public void run() { try { for (int i = 0; i < 100; i++) { System.out.println( "Runnable "+i); Thread.sleep(sleep); } } catch (InterruptedException e) { e.printStackTrace(); } } public MyRunnable(int sleep) { super(); this.sleep = sleep; } } Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 13 Thread & Runnable MyThread t1 = new MyThread(100); t1.setName("t1"); t1.setPriority(Thread.MIN_PRIORITY); MyThread t2 = new MyThread(100); t2.setName("t2"); t2.setPriority(Thread.MAX_PRIORITY); //MyRunnable r1 = new MyRunnable(200); Thread t3 = new Thread(new MyRunnable(200)); t1.start(); t2.start(); //r1.run(); t3.start(); Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 14 Synchronization  Synchronization in java is the capability to control the access of multiple threads to any shared resource.  The synchronization is mainly used to to prevent thread interference. ‫منع تداخل‬ to prevent consistency problem. ‫االتساق‬  Mutual Exclusive, a thread synchronization, helps keep threads from interfering with one another while sharing data. This can be done by three ways in java: by synchronized method by synchronized block by static synchronization Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 15 Method Synchronization  When a thread invokes a synchronized method, it automatically acquires the lock for that object (method) and releases it when the thread completes its task. public synchronized String getData(File f) { String s = ""; try { Scanner sc = new Scanner(f); while (sc.hasNextLine()) s += sc.nextLine()+"\n"; } catch (FileNotFoundException e) { e.printStackTrace(); } return s; } Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 16 Block Synchronization  Synchronized block can be used to perform synchronization on any specific resource of the method. Synchronized block is used to lock an object for any shared resource. Scope of synchronized block is smaller than the method. public void getData() { File f = new File("testfile.txt"); synchronized (f) { // synchronized (this) try { Scanner sc = new Scanner(f); while (sc.hasNextLine()) System.out.println(sc.nextLine()); } catch (FileNotFoundException e) { e.printStackTrace(); } } } Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 17 Static Synchronization  Making a static method as synchronized, the lock will be on the class not on object. Problem without static synchronization, there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lock. public static synchronized String getData(File f) { String s = ""; try { Scanner sc = new Scanner(f); Jan 18, 2025... Created by: Dr. Abdelkareem Alashqar 18 Threads Pool & Executers  A thread pool is an instance of ExecutorService class. With an ExecutorService, you can submit task that will be completed in the future.  There are five types of thread pools which can be created with the Executors class: 1. Single Thread Executor : A thread pool with only one thread. So all the submitted tasks will be executed sequentially. Executors.newSingleThreadExecutor() 2. Cached Thread Pool : A thread pool that creates as many threads it needs to execute the task in parrallel. The old available threads will be reused for the new tasks. If a thread is not used during 60 seconds, it will be terminated and removed from the pool. Executors.newCachedThreadPool() Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 19 Threads Pool & Executers … 3. Fixed Thread Pool : A thread pool with a fixed number of threads. If a thread is not available for the task, the task is put in queue waiting for an other task to ends. Executors.newFixedThreadPool() 4. Scheduled Thread Pool : A thread pool made to schedule future task. Executors.newScheduledThreadPool() 5. Single Thread Scheduled Pool : A thread pool with only one thread to schedule future task. Executors.newSingleThreadScheduledExecutor() Jan 18, 2025 Created by: Dr. Abdelkareem Alashqar 20 Threads Pool & Executers public static void main(String[] args) { ExecutorService s = Executors.newFixedThreadPool(3); for (int i =1; i

Use Quizgecko on...
Browser
Browser