(Established under the Presidency University Act, 2013 of the Karnataka Act 41 of 2013)
CSE3146 – Advanced JAVA Programming
LAB SHEET - 1
Module 1- Multithreading using Java
Q1. Create a single thread by implementing Runnable interface.
Solution:
Step 1: Start
Step 2: Create a class Task that implements builtin interface Runnable
Step 3: Override run() to define work of thread. Use [Link]() to print the thread is running
currently
Step 4: Create object task of Task.
Step 5: Create object of Thread by passing task as parameter
Step 5: Assign a name to thread using setName(“Name”)
Step 6: Call start() to start the thread
Step 7: Stop
import [Link].*; //optional
class Task implements Runnable {
public void run() {
[Link]([Link]()+" printing ");
[Link]("Welcome");
}
}
public class TestThread {
public static void main(String[] args) {
Task task = new Task();
Thread t1= new Thread(task);
[Link]("first");
[Link]();
[Link]([Link]()+" printing ");
[Link]("to Java");
}
}
Q2. Create a single thread by extending Thread class
Solution:
Step 1: Start
Step 2: Create a class MyThread that extends builtin class Thread
Step 3: Override run() to define work of thread. Use [Link]() to print the thread is running
currently
Step 4: Create object of MyThread
Step 5: Assign a name to thread using setName(“Name”)
Step 6: Call start() to start the thread
Step 7: Stop
class MyThread extends Thread {
// run() method to perform action for thread.
public void run()
{
int a= 10;
int b=12;
int result = a+b;
[Link]([Link]()+" started
running..");
[Link]("Sum of two numbers is: "+ result);
[Link]([Link]()+" completed..");
}
}
public class TestThread {
public static void main( String args[] )
{
[Link]([Link]()+" started");
// Creating instance of the class extend Thread class
MyThread t = new MyThread();
[Link]("first");
//calling start method to execute the run() method of the
Thread class
[Link]();
[Link]([Link]()+" completed");
}
}
Q3: Create 3 threads 1st, 2nd and 3rd to print numbers 5 to 1 concurrently by extending Thread Class.
Requirement:
• Override run() to print 5 to 1 using for loop
• Use sleep() for switching the context to other threads
• Use setName() to set the name of Thread or Use constructor Thread() to set the name of
Thread
Sol:
class MyThread extends Thread {
String name;
MyThread (String name){
setName(name); or // super(name);
[Link]=name;
[Link]( "A New thread: " + name + "is created\n" );
}
public void run() {
try {
for(int j = 5; j > 0; j--) {
[Link](name + ": " + j);
[Link](1000);
}
}catch (InterruptedException e) {
[Link](name + " thread Interrupted");
}
[Link](name + " thread exiting.");
}
}
public class TestMultiThread {
public static void main(String args[]) {
MyThread t1=new MyThread(“one”);
MyThread t2=new MyThread(“two”);
MyThread t3=new MyThread(“three”);
[Link]();
[Link]();
[Link]();
try {
[Link](8000);
} catch (InterruptedException excetion) {
[Link]("Inturruption occurs in Main Thread");
}
[Link]("We are exiting from Main Thread");
}
Q4: Create 3 threads 1st, 2nd and 3rd to print factorial of three different numbers concurrently by
extending Thread Class.
Requirement:
• Override run() to print factorial using for loop
• Use sleep() for switching the context to other threads
• Use constructor Thread() to set the name of Thread
• Demonstrate join() and isAlive() method
Sol:
class MyThread extends Thread {
String name;
int number;
long fact=1;
MyThread (int number,String name){
super(name); //calling Thread()
[Link]=number;
[Link]=name;
[Link]( "A New thread: " + name + " is created\n" );
}
public void run() {
try {
for(int i = 1; i <= number; i++) {
[Link](name + " calculating factorial");
fact=fact*i;
[Link](1000);
}
}catch (InterruptedException e) {
[Link](name + " thread Interrupted");
}
[Link](name + " calculated factorial "+fact);
} }
public class TestMultiThread {
public static void main(String args[]) {
MyThread t1=new MyThread(5,"one");
MyThread t2=new MyThread(4,"two");
MyThread t3=new MyThread(3,"three");
[Link]();
[Link]();
[Link]();
[Link]("1st Alive : "+[Link]());
[Link]("2nd Alive : "+[Link]());
[Link]("3rd Alive : "+[Link]());
try {
[Link]();
[Link]();
[Link]();
[Link]("1st Alive : "+[Link]());
[Link]("2nd Alive : "+[Link]());
[Link]("3rd Alive : "+[Link]());
} catch (InterruptedException excetion) {
[Link]("Inturruption occurs in Main Thread");
}
[Link]("We are exiting from Main Thread");
}
}
Q5: Create three threads by setting different priorities to each thread.
Sol:
class ThreadPrior extends Thread {
public void run()
{
// Print statement
[Link]("Inside run method");
}
}
public class TestThreadPrior {
public static void main(String[] args)
{
ThreadPrior t1 = new ThreadPrior();
ThreadPrior t2 = new ThreadPrior();
ThreadPrior t3 = new ThreadPrior();
[Link]("t1 thread priority : "+ [Link]());
[Link]("t2 thread priority : "+ [Link]());
[Link]("t3 thread priority : "+ [Link]());
[Link](2);
[Link](5);
[Link](8);
[Link](21); //error
[Link]("t1 thread priority : " + [Link]());
[Link]("t2 thread priority : "+ [Link]());
[Link]("t3 thread priority : " + [Link]());
// Main thread
[Link]("Currently Executing Thread :
"+[Link]().getName());
[Link](
"Main thread priority : "+ [Link]().getPriority());
// Main thread priority is set to 10
[Link]().setPriority(10);
[Link](
"Main thread priority : "+ [Link]().getPriority());
}
}
Q6: Demonstrate Thread Synchronization for a given resource to avoid race condition.
• Create a Resource class to keep two resources [ and ]. No thread can take ] without [
• Create three threads to access the above resource without synchronization
• Access the above resource using synchronization
Sol:
class Resource {
void use(String name) {
[Link]("[" + name);
try {
[Link](1000);
} catch(InterruptedException e) {
[Link]("Interrupted");
}
[Link]("]");
}
}
class MyThread extends Thread {
String name;
Resource r;
MyThread (String name,Resource r){
super(name);
[Link] = name;
this.r=r;
}
public void run() {
synchronized(r) {
[Link](name);
}
}
}
public class TestMultiThread {
public static void main(String args[]) {
Resource res=new Resource();
MyThread t1=new MyThread("1st",res);
MyThread t2=new MyThread("2nd",res);
MyThread t3=new MyThread("3rd",res);
[Link]();
[Link]();
[Link]();
try {
[Link]();
[Link]();
[Link]();
} catch (InterruptedException excetion) {
[Link]("Inturruption occurs in Main Thread");
}
}
}
Record Writing
Note: Submit the record on or before the due date.
Both Soft and Hard copies are required to be submitted.
RECORD WRITING INSTRUCTIONS
1. Solve the programming exercise using any IDE (Laptop / Mobile) or using any online compiler.
A. Students can use online compiler or any preferable platform for the execution. Suggested is to
use JDoodle. [Link] Do test this site before your CA.
B. Mobile users, kindly install JStudio - ide for java [Link]
id=[Link]&hl=en. This instruction is already given for solving your lab
programs. If you haven’t done, please do install, and test the app as soon as possible.
2. While solving your programming exercise, write the code in A4 sheet paper/Record. While writing
on the paper, please add these info. “Presidency University” “Department of CSE” “Odd semester
2021- 2022” “MODULE - 1" “Course code : CSA 1005”, Course name : OOP Using JAVA, ID: ,
NAME: , SEC: , Date: _
A. While coding (the soft copy) & writing in the paper/record, all your CLASS NAME and the
METHOD NAME must be appended with your LAST FOUR DIGIT student ID. This is
mandatory, even while WRITING in the paper/record.
For example: If your class sample0161 {
Registration number is void Method0161(parameterlist) {
2020BCA0161 then //method body
B. Take a screenshot of your program & the output from your mobile/laptop.
C. Take a photo of the handwritten program.
D. Put together (4. A,B,C) , combine as one pdf, with the file name as your student
registration number(ex. [Link]), and upload the file in Camu.
E. The document must be uploaded within the specified time in Camu.
Kindly follow the instructions very carefully so that your submission will be valid.