Cloud Lab 4

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Lab 4 : Implement Multi Thread programming using Java

Objective: Execute multiple threads simultaneously to optimize


computing resources.

Introduction
Multithreading in Java is a process of executing multiple threads simultaneously.
Multithreading makes multitasking possible when it breaks programs into smaller,
executable threads. Each thread has the programming elements needed to execute the
main program, and the computer executes each thread one at a time. Threads can be
created by using two mechanisms :

1. Extending the Thread class

2. Implementing the Runnable Interface

Multithreading in Cloud Computing

Multithreading in cloud computing serves several purposes and can be beneficial for various
aspects of cloud-based applications and services. Purpose of using Multithreading in cloud
computing:

1. Improved Performance

2. Scalability

3. Resource Efficiency

4. Parallel Processing

Program
An example that creates a new thread implementing Runnable interface and starts running
it.
public class lab4 implements Runnable {
private Thread t;
private String threadName;
lab4(String name){
threadName = name;
System.out.println("Creating "+ threadName );
}
public void run() {
System.out.println("Running " + threadName );

try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + " , " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch(InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println(" Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}

public class TestThread {


public static void main(String args[]) {
lab4 R1 =new lab4("Thread-1 " );
R1.start();
lab4 R2 = new lab4("Thread-2 ");
R2.start();
}
}
Output :
Conclusion :

A thread instance can also be created using the Runnable interface. To create a thread
instance, the class whose objects should be executed by a thread should implement the
Runnable interface. From above program the output has been observed for multithreading.

You might also like