Lab Manual Course Code: CS2131 Semester-III: Object Oriented Programming Lab
Lab Manual Course Code: CS2131 Semester-III: Object Oriented Programming Lab
Lab Manual
Object Oriented programming Lab
Course Code: CS2131
Semester-III
Department of Computer Science and Engineering
School of Computing & Information Technology
Lab 8: Multithreading
Objective:
Scope:
Exercises:
Exercise 1:
Create an example of a “busy wait.” One thread sleeps for a while and then sets a
flag to true. The second thread watches that flag inside a while loop (this is the
“busy wait”) and when the flag becomes true, sets it back to false and reports the
change to the console. Note how much wasted time the program spends inside the
“busy wait” and create a second version of the program that uses wait( ) instead
of the “busy wait.”
Exercise 2:
Write a program that runs 5 threads, each thread randomizes a number between
1 and 10. The main thread waits for all the others to finish, calculates the sum of
the numbers which were randomized and prints that sum. You will need to
implement a Runnable class that randomizes a number and store it in a member
field. When all the threads have done, your main program can go over all the
objects and check the stored values in each object.
Exercise 3:
Modify the program in (Ex. 2) so that instead of each object keeping its own score,
you will use one collection to store all the results in.
Department of Computer Science and Engineering
School of Computing & Information Technology
Exercise 4:
XYZ company has offices in different cities and wants to lay down the wire, to connect them with
each other. The wire cost is different to connect different pairs of cities. The notation is represented
in the following figure.
Here edges are undirected and numbers over edge represent the cost of wire. When two edges
are connected to the same pair of cities and cost of wire is different than it is called parallel edge.
If start and end city of an edge are same, then it is called loop. Consider the following declaration.
Homework
Exercise 1
Write a program to create two threads. In this class we have one constructor used to start
the threads and run it. Check whether these two threads are run or not.
Exercise 2
Create a multithreaded program by using Runnable interface and then create, initialize
and start three Thread objects from your class. The threads will execute concurrently
and display the following String array elements.
String course [ ] = {“Java”, “J2EE”, “Spring”, “Struts”};
Exercise 3
Write a program for inventory problem to illustrate the usage of synchronized keyword.
Note: The output should be similar as mentioned below:
Thread1Thread[test thread,5,main]
Thread2Thread[test thread,5,main]
Quantity ordered :13