Docsity

Multithreading in Java part 7, Study notes of Computer science

Partial preview of the text

Download Multithreading in Java part 7 and more Study notes Computer science in PDF only on Docsity!

Chapter 8: Multithreading in Java 8.1 Introduction ¢ Multitasking — Performing multiple tasks at the same time. * Multithreading — A type of multitasking where a program (process) runs multiple threads simultaneously. e A thread is the smallest unit of execution in a program. « Example: A text editor can check spelling, save files, and allow typing at the same time. 8.2 Advantages of Multithreading 1. Efficient CPU utilization. 2. Improves performance by parallel execution. 3. Useful for animations, games, multimedia. 4. Reduces idle time of system resources. 8.4 Creating Threads in Java There are two ways to create threads: 1. By extending the Thread class Java class MyThread extends Thread { public void run() { System.out.println( "Thread PRANLNB 00 7): } public static void main(String[] args) { MyThread t1 = new MyThread(); ti.start(); // starts thread, calls run() } } 2. By implementing the Runnable interface Java class MyRunnable implements Runnable { public void run() { System.out.println¢("Thread running..."); t public static void main(String[] args) { Thread t1 MyRunnable()); t1.start(); new Thread(new } Example: Using synchronized keyword Java class Counter { int count = 0; synchronized void increment() { count++; } } class Test { public static void main(String[] args) throws Exception { Counter c = new Counter(); Thread t1 = new Thread(() -> { for(int i=0;i<1000;i++) c.increment(); hb) Thread t2 = new Thread(¢) -> { forcint i=0;1<1000;i++) c.increment(); ier ti.startd); t2.startd); ti. join(); t2.join(); System.out.println(c.count); // 2000 8.8 Inter-Thread Communication ¢ Threads can communicate using methods of Object class: a. wait() > Makes thread wait. b. notify() = Wakes up one waiting thread. Cc. notifyAll() = Wakes up all waiting threads. 8.9 Daemon Threads *« Daemon thread: Runs in the background (e.g., Garbage Collector). ¢ Ends automatically when all user threads finish. Java class Test extends Thread { public void rund) { if(Thread.currentThread( ). isDaemon()) System. out. println( "Daemon thread running"); else System, out. printin("User thread running"); } public static void main(String[] args) { Test t = new Test(); t.setDaemon(true); t.start();