Home CPSC 240

Lab 15: Threads

 

Objective

To gain experience working with multi-threaded programming.


 

Task

For this lab, you will parallelize a sequential algorithm. This Search.java program contains a class called Set. This class has an add method for adding names to the set, and an exists method for testing whether an element is in the set.

The main class creates a Set, adds 100 names to it, and then tests 10 names for membership in the set.

Your task is to change the "exists" function so that it splits the work into two independent threads. You can do this by having one thread search the first half and the second thread search the second half.

In order to make sure you are really parallelizing the search, you should have the thread print a message with its thread number when it finds the name.


 

Details

  1. Create a class called SearchThread that extends the Thread class. It should store everything it needs to do the job of searching part of a list: the start and end points, the list, and the thing to search for. These should be passed into the constructor.
  2. Have the SearchThread's run() method do the job of searching its portion of the list. It should print out when it finds the target name. It should also store into a boolean instance variable whether it was successful or not.
  3. The Set's exists() method should be re-written to create two SearchThread objects. It should pass in the data needed for each to do its search.
  4. The exists() method should then start and then join both threads.
  5. Finally it can ask each SearchThread object if it found the target string or not and return true or false based off that.
  6. The main method should not need to be changed for this.

 

Testing

Your program should find every other name on the list. The original program produces the following:

Ivy exists: true.
Mark exists: false.
Pearl exists: true.
Georgette exists: false.
Simone exists: true.
Bobby exists: false.
Roland exists: true.
Agatha exists: false.
Luz exists: true.
Herman exists: false.

The behavior of your program should be identical, but should also include which thread found the name, like this:

Thread 2 found the name.
Ivy exists: true.
Mark exists: false.
Thread 1 found the name
Pearl exists: true.
Georgette exists: false.
Thread 2 found the name.
Simone exists: true.
Bobby exists: false.
Thread 1 found the name
Roland exists: true.
Agatha exists: false.
Thread 2 found the name.
Luz exists: true.
Herman exists: false.

 

Submitting

When you are done, please submit the Java code under the assignment in Canvas.

Copyright © 2022 Ian Finlayson | Licensed under a Attribution-NonCommercial 4.0 International License.