JPL Assignment 05
JPL Assignment 05
Aim: Write a java program that implements a multi-thread application that has three
threads. First thread generates a random integer every 1 second and if the value is even,
the second thread computes the square of the number and prints. If the value is odd,
the third thread will print the value of the cube of the number.
Pre-Requisites: C/C++
Outcomes:
Theory:
Multithreading is a Java feature that allows concurrent execution of two or more parts of
a program for maximum utilization of CPU. Each part of such program is called a thread.
So, threads are light-weight processes within a process.
We create a class that extends the java.lang.Thread class. This class overrides the run()
method available in the Thread class. A thread begins its life inside run() method. We
create an object of our new class and call start() method to start the execution of a
thread. Start() invokes the run() method on the Thread object.
// Java code for thread creation by extending
try {
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
// Main Class
object.start();
Output:
Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running
We create a new class which implements java.lang.Runnable interface and override run()
method. Then we instantiate a Thread object and call start() method on this object.
// Java code for thread creation by implementing
try {
+ " is running");
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
// Main Class
class Multithread {
object.start();
Output
Thread 13 is running
Thread 11 is running
Thread 12 is running
Thread 15 is running
Thread 14 is running
Thread 18 is running
Thread 17 is running
Thread 16 is running
Algorithm/Steps:
2.Create a class with the name “even implements Runnable” and “odd
implementsRunnable”.
CODE:
/*Problem Statement: Write a Java program that implements a multi-thread application that
has three threads. First thread generates a random integer every 1 second and if the value is
even, the second thread computers the square of the number and prints. If the value is odd,
third thread will print the value of the cube of the number.*/
//@Author:Harsh Sonigara
//Roll No: 2213220
//Class: SY-4 Batch A
//CODE:
import java.util.Random;
if((randomInteger%2) == 0) {
sThread.start();
else {
cThread.start();
try {
Thread.sleep(1000);
System.out.println(ex);
}
}
int number;
SquareThread(int randomNumbern) {
number = randomNumbern;
int number;
CubeThread(int randomNumber) {
number = randomNumber;
rnThread.start();
OUTPUT: