Java 4thworksheet
Java 4thworksheet
WORKSHEET 4
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);
}}}
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.