Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

Oops Through Java Unit IV

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Oops Through Java Unit IV

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

OOPS THROUGH JAVA - UNIT IV

Java provides powerful built-in support for multithreaded programming,


allowing for the creation of programs that can handle multiple tasks
concurrently. In a multithreaded program, different parts, called threads, execute
in parallel, each with its own execution path. This enables Java applications to
perform tasks concurrently within a single program, efficiently utilizing system
resources.

Introduction to Multithreading and Multitasking

Multithreading is a specialized form of multitasking where a single program


divides its work into multiple, concurrently running threads. This is in contrast
to process-based multitasking, which involves running multiple separate
programs simultaneously. Multithreading allows Java applications to operate
more responsively and efficiently, especially in environments where multiple
tasks need to be handled at once.

For example, consider a multimedia application: it can play music, display


visuals, and respond to user input all at the same time. With multithreading,
each of these activities can run on a separate thread, making the application
responsive and efficient.

Key Benefits of Multithreading in Java


- Resource Efficiency: Threads are lightweight and consume less memory
than processes. Thread creation and management require fewer resources,
reducing program overhead.
- Shared Memory: Threads within the same process share memory,
allowing them to work closely together. This enables simpler
communication compared to processes, which require complex inter-
process communication (IPC).
- Better Performance: Java threads improve program responsiveness by
allowing time-slicing among tasks, ensuring smoother execution.
Key Concepts of Multithreading

Example of Multithreading in a Word Processor


In a word processor, multiple activities, such as typing, spell-checking, and
printing, can occur simultaneously:
- Typing Thread: Continuously captures and displays user input.
- Spell-Check Thread: Monitors and flags spelling errors in real time.
- Print Thread: Allows the user to print a document in the background while
continuing to type.

Life Cycle of a Thread in Java


Java threads can exist in six different states, reflecting the phases from creation
to completion:

1. NEW: A thread that has been created but not yet started.
2. RUNNABLE: A thread that is ready to run but is either executing or waiting
for CPU time.
3. BLOCKED: A thread that is waiting to acquire a lock to enter a synchronized
block or method.
4. WAITING: A thread that is waiting indefinitely until another thread performs
a specific action.
5. TIMED_WAITING: A thread that is waiting for another thread to perform a
specific action for a specified amount of time.
6. TERMINATED: A thread that has completed its execution.

This life cycle reflects the complex interplay between Java threads and system
resources, with transitions between states managed by the Java Virtual Machine
(JVM) based on the program’s logic and resource availability.

Creating Threads in Java


Java provides two primary ways to create a thread:
1. Implementing the Runnable Interface
2. Extending the Thread Class

1. Implementing the Runnable Interface


Implementing `Runnable` is the preferred approach when you want the thread to
be part of a class that extends another class. By implementing `Runnable`, you
can create threads without restricting your class inheritance.

Example: Implementing Runnable


public class MainRunnableExample implements Runnable {
public static void main(String[] args) {
MainRunnableExample runnable = new MainRunnableExample();
Thread thread = new Thread(runnable);
thread.start();
System.out.println("This code is outside the thread");
}

public void run() {


System.out.println("This code is running in a separate thread");
}
}

2. Extending the Thread Class


Extending the `Thread` class is another way to create a thread in Java. This is
simpler but less flexible if your class needs to inherit from another class since
Java does not support multiple inheritance.

Example: Extending Thread


public class MainThreadExample extends Thread {
public static void main(String[] args) {
MainThreadExample thread = new MainThreadExample();
thread.start();

System.out.println("This code is outside the thread");


}

public void run() {


System.out.println("This code is running in a separate thread");
}
}
Key Differences between Extending Thread and Implementing Runnable
The major difference between extending the `Thread` class and implementing
the `Runnable` interface is in inheritance flexibility:
- Extending Thread: If you extend `Thread`, you cannot extend any other class.
- Implementing Runnable: Allows your class to extend another class, enabling
more flexible class structures.

Example: Runnable Interface with Inheritance


class ParentClass {
public void showMessage() {
System.out.println("Message from ParentClass.");
}
}

class ChildClass extends ParentClass implements Runnable {


@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
}
}

public class RunnableWithInheritanceExample {


public static void main(String[] args) {
ChildClass obj = new ChildClass();
Thread thread = new Thread(obj);
thread.start();

// Call method from ParentClass


obj.showMessage();

System.out.println("This code is outside of the thread");


}
}
```

Java Thread Example - Demonstrating Multithreading with Multiple


Threads
This example shows how multiple threads work together in Java, demonstrating
simultaneous execution of two tasks.

class TaskOne implements Runnable {


public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Task One - Count: " + i);
try {
Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); }
}
}
}

class TaskTwo extends Thread {


public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Task Two - Count: " + i);
try { Thread.sleep(700); } catch (InterruptedException e)
{ e.printStackTrace(); }
}
}
}

public class MultiThreadExample {


public static void main(String[] args) {
Thread thread1 = new Thread(new TaskOne());
TaskTwo thread2 = new TaskTwo();

thread1.start();
thread2.start();

System.out.println("Both tasks started concurrently.");


}
}

In this example:
- TaskOne runs with a `Runnable` implementation, allowing it to be wrapped in
a `Thread`.
- TaskTwo directly extends `Thread`, enabling direct instantiation and `start()`
invocation.

Use of Thread.sleep(int milliseconds)

The purpose of Thread.sleep() in Java is to pause the execution of the current


thread for a specified amount of time. When Thread.sleep(milliseconds) is
called, the thread pauses (or "sleeps") for the given duration in milliseconds,
allowing other threads to execute and use CPU resources during this time.
The main jobs of the Thread.sleep() method are:
1. Adding pauses in a program: This helps to make programs run at a
realistic speed, create slow-motion effects, and pause for a little while
(like in games).
2. Reducing computer work: When a part of a program does the same thing
over and over, Thread.sleep() helps by making the computer rest a bit
between each time it does it.
3. Letting other parts of the program work: Pausing a part of a program lets
other parts do their jobs, which is important when many parts of a
program are working together.
4. Waiting for outside help: Sometimes, parts of a program need to wait for
something from outside the program, like information from the internet or
information from a disk. Thread.sleep() helps with this by making the
program wait a bit.

You might also like