[Go to site: main page, start]

0% found this document useful (0 votes)
7 views12 pages

Java Multithreading Basics and Examples

Uploaded by

mevoni8999
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views12 pages

Java Multithreading Basics and Examples

Uploaded by

mevoni8999
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Multithreading

Multithreading in Java is a feature that allows multiple tasks to run concurrently


within the same program. Instead of executing one task at a time, Java enables
parallel execution using lightweight threads. This makes applications more
efficient, faster and responsive in real-world scenarios like servers, games and
chat systems.

Thread Methods
Java provides built-in methods like start(), run(), sleep() and join() to manage
thread execution and control its behavior.
 start() Method
 suspend() Method
 stop() Method
 wait() Method
 notify() Method
 notifyAll() Method
 sleep() Method
 join() Method
class Buddy1 extends Thread //myThread1
{
public void run()
{
[Link]("Thread1 is running");
}
}

class Buddy2 extends Thread //mythread2


{

public void run()


{
[Link]("Thread2 is running");
}
}

class Main
{
public static void main(String[] args)
{
Buddy1 obj1 = new Buddy1 ();
Buddy2 obj2 = new Buddy2();
[Link]();
[Link]();
}
}
Output
Thread1 is running
Thread2 is running
Lifecycle and States of a Thread in Java
A thread in Java can exist in any one of the following states at any given time. A
thread lies only in one of the shown states at any instant:
1. New State
2. Runnable State
3. Blocked State
4. Waiting State
5. Timed Waiting State
6. Terminated State
The diagram below represents various states of a thread at any instant:

class Bunny extends Thread

public void run()

for(int i=1;i<=5;i++)

[Link](i);

}
}

class Bunny1

public static void main(String args[])

Bunny b=new Bunny();

[Link]();

class Bunny extends Thread

public void run()

for(int i=1;i<=5;i++)

[Link]("KNTPNTRTVTJT");

class Bunny1

public static void main(String args[])

Bunny b=new Bunny();

[Link]();
for(int i=1;i<=5;i++)

[Link]("Hello Java Program");

C:\Users\hp\Desktop>javac [Link]

C:\Users\hp\Desktop>java Bunny1

Hello Java Program

Hello Java Program

Hello Java Program

Hello Java Program

Hello Java Program

KNTPNTRTVTJT

KNTPNTRTVTJT

KNTPNTRTVTJT

KNTPNTRTVTJT

KNTPNTRTVTJT

*/

class Bunny extends Thread

//if we are used throws with run() does not execute because of give interruped error and
sove by try...catch keywords

public void run() //throws InterruptedException


{

for(int i=1;i<=5;i++)

[Link]("KNTPNTRTVTJT");

//[Link](1000);

class Bunny1

public static void main(String args[]) throws InterruptedException

Bunny b=new Bunny();

[Link]();

[Link](1000);

for(int i=1;i<=5;i++)

[Link]("Hello Java Program");

class Bunny extends Thread

public void run() //throws InterruptedException(is write down in this block then error is
show)
{

try

for(int i=1;i<=5;i++)

[Link]("KNTPNTRTVTJT");

[Link](1000);

catch(InterruptedException k)

[Link](k);

class Bunny1

public static void main(String args[]) throws InterruptedException

Bunny b=new Bunny();

[Link]();

[Link](1000);

for(int i=1;i<=5;i++)

[Link]("Hello Java Program");


}

C:\Users\hp\Desktop>javac [Link]

C:\Users\hp\Desktop>java Bunny1

KNTPNTRTVTJT

KNTPNTRTVTJT

Hello Java Program

Hello Java Program

Hello Java Program

Hello Java Program

Hello Java Program

KNTPNTRTVTJT

KNTPNTRTVTJT

KNTPNTRTVTJT(runtime output is always changes)

class Bunny extends Thread

//@override

public void Run() //throws InterruptedException(is write down in this block then error is
show)

try

for(int i=1;i<=5;i++)

{
[Link]("KNTPNTRTVTJT");

[Link](1000);

catch(InterruptedException k)

[Link](k);

class Bunny1

public static void main(String args[]) throws InterruptedException

Bunny b=new Bunny();

[Link]();

[Link]();

for(int i=1;i<=5;i++)

[Link]("Hello Java Program");

[Link](1000);

C:\Users\hp\Desktop>javac [Link]
C:\Users\hp\Desktop>java Bunny1

KNTPNTRTVTJT

KNTPNTRTVTJT

KNTPNTRTVTJT

KNTPNTRTVTJT

KNTPNTRTVTJT

Hello Java Program

Hello Java Program

Hello Java Program

Hello Java Program

Hello Java Program

*/

class Bunny implements Runnable

public void run()

[Link]("Hello Thread Program by Runnable Interface");

class Bunny1

public static void main(String args[])

Bunny b=new Bunny();

Thread t=new Thread(b);


[Link]();

for(int i=1;i<=5;i++)

[Link]("Main thread closed");

C:\Users\hp\Desktop>javac [Link]

C:\Users\hp\Desktop>java Bunny1

Main thread closed

Main thread closed

Main thread closed

Main thread closed

Main thread closed

Hello Thread Program by Runnable Interface

Common questions

Powered by AI

The Blocked State occurs when a thread is unable to proceed because it is waiting for a lock that another thread holds, often encountered in synchronized block competition scenarios. The Waiting State, however, occurs when a thread waits indefinitely until it is notified by another, commonly seen in inter-thread communication scenarios using wait() and notify() methods. These states distinctly manage synchronization and communication, addressing different multithreading design needs .

The Runnable interface separates the task being performed by the thread from the thread itself, leading to a cleaner design as the logic is not tied directly to the thread mechanics. This allows for a class to implement multiple interfaces and encapsulates the task code independently from Thread instantiation and execution mechanisms. This enhances flexibility, for example, when threads are required to execute the same code, as multiple threads can be created using a Runnable instance .

Using the start() method initiates a new thread and calls the run() method asynchronously, allowing parallel execution. Conversely, calling run() directly does not start a new thread but executes the run() method in the current thread context, leading to sequential processing without actual concurrency. This distinction is critical in leveraging Java's multithreading capabilities for task parallelism .

Exception handling is crucial in Java thread execution to manage runtime anomalies without terminating the program. Methods like sleep() and join() can throw InterruptedExceptions if a thread is interrupted while sleeping or waiting. Proper handling ensures that the program can gracefully recover or exit, thereby enhancing reliability and robustness, which is essential in multithreaded applications where interruptions are part of normal operations .

A thread in Java can exist in several states, each impacting its execution flow. The New state is when the thread is created but not yet started. Runnable state means the thread is ready to run and is waiting for CPU time. A Blocked state occurs when a thread is waiting for a monitor lock. The Waiting state is when a thread is waiting indefinitely for another thread to perform a particular action. In the Timed Waiting state, a thread is waiting for another to perform an action within a specific timeframe. Finally, the Terminated state signifies that the thread has completed its execution, indicating different resource usages and behavioral patterns .

The synchronized keyword in Java ensures that only one thread can access a synchronized resource or block of code at a time. It provides a lock for the object being accessed, preventing race conditions and ensuring thread safety by guaranteeing atomicity of operations within the synchronized block. This plays a critical role in resource sharing or modifying shared data across multiple threads, thereby preventing data inconsistency .

The stop() method can lead to inconsistent states because it abruptly terminates a thread without giving it a chance to release resources properly or finalize data. Similarly, suspend() can cause deadlocks because it suspends a thread without releasing the locks it holds, blocking others from accessing those resources. Consequently, these methods can cause unpredictable behavior, making programs hard to debug, and are therefore discouraged in favor of using alternatives like interrupt() for more controlled termination .

An InterruptedException occurs when a thread is interrupted while its execution is paused. To resolve this, wrap potentially interruptible code in a try-catch block. Upon catching these exceptions, you can either re-interrupt the current thread or handle it softly by cleaning up resources and ending the task gracefully. Best practices dictate that you're clear about task interruption points and manage state consistency to avoid incorrect or incomplete operations .

Implementing threads with the Runnable interface is advantageous when extending from another class since Java does not support multiple inheritance. This approach promotes the decoupling of task logic from the thread management logic. It also allows multiple threads to share the same task instance, potentially conserving resources in certain applications like thread pools .

Java provides several methods to manage thread execution and control its behavior. These include start(), run(), sleep(), and join(). The start() method creates a new thread and starts its execution. The run() method contains the code meant to be executed by the thread. The sleep() method temporarily suspends the current thread for a specified period, allowing others to execute. The join() method allows one thread to wait until another thread completes its execution, ensuring a sequence of task completions .

You might also like