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

DEPRTMENT OF

COMPUTER SCIENCE & ENGINEERING

WORKSHEET 4

Name: Hrishabh Gupta UID: 22BCS50102

Branch: CSE Section/Group: 902 -B

Semester: 3rd Date of Performance: 31-10-2023

Subject Name: Java Programming Subject Code: 22CSH-201

1. Aim: Create a program with two threads, one is printing even numbers and other is printing
odd numbers up to 50.

2. Source Code:
import java.io.*;
class CheckNo {
synchronized void function(){
System.out.println();
System.out.print("Even no is : ");
for (int i=0;i<50;i++) {
if (i%2==0) {
System.out.print(i+" ");
}
try {
Thread.sleep(50);
}
catch (Exception e) { System.out.println(e);
}}}

synchronized void function2()


{System.out.println();
System.out.print("Odd no is : ");
for (int i=0;i<50;i++) {
if (i%2!=0) {
System.out.print(i+" ");
}
try {
Thread.sleep(50);
}
catch (Exception e) { System.out.println(e);
}}}}

public class Main {


public static void main(String args[])
{
DEPRTMENT OF
COMPUTER SCIENCE & ENGINEERING
CheckNo obj = new CheckNo();
Thread a = new Thread() {
public void run() { obj.function(); }
};
Thread b = new Thread() {
public void run() { obj.function2(); }
};
a.start();
b.start();
}}
3. Screenshot of Outputs:

4. Learning Outcomes :

• Gain knowledge about using the synchronized keyword with blocks and methods to
restrict access to critical sections of code, thereby allowing only one thread at a time to
execute these sections.
• Understand how race conditions and concurrent access to shared resources can lead to
unexpected behavior in the absence of synchronization.
• Understand the concept of locks and monitors in Java to manage access to shared
resources among multiple threads.
• Understand the concept of exception handling in Java to manage access to handle
potential exceptions that may occur during thread execution.

You might also like