14.1. Quick Introduction

14.1.1. Introduction Video

In the following video, we introduce the concept of a thread and provide some code examples to illustrate how threads can be used to make your program execute two or more pieces of code concurrently (i.e., they appear to be executing at the same time). Many of the definitions presented in this video are simplified in order to make them more approachable for beginners.

14.1.2. Setting up the Starter Code

  1. Use the following command to download the starter code used in the introduction video and place it into a subdirectory called cs1302-threads:

    sh -c "$(curl -fsSl https://cs1302uga.github.io/cs1302-book/_bundle/cs1302-threads.sh)"
    
  2. Change into the cs1302-threads directory that was just created and look around. There should be multiple Java files contained in the src directory. To see a listing of all of the files under the cs1302-threads directory, use the tree command as follows:

    tree
    
    .
    ├── compile.sh
    ├── run.sh
    └── src
        └── cs1302
            └── threads
                └── ThreadDriver.java
    
    4 directories, 3 files
    
  3. You can compile and run the starter code using the provided scripts:

    ./compile.sh
    
    + mkdir -p bin
    + javac -d bin src/cs1302/threads/ThreadDriver.java
    
    ./run.sh
    
    + java -cp bin cs1302.threads.ThreadDriver
    ...
    

    Important

    Use C-c to terminate the program. Do NOT use C-z as that only stops the program (i.e., it minimizes the program into the background). You can use the jobs command to periodically check if you have any stopped jobs and the fg command to bring a stopped job back into the foreground so that you can termiante it with C-c.

  4. Play with the code and try things out!

    Test Yourself!

    Adjust the starter code so that it can execute four infinite loops concurrently.

    1. Up to how many threads is your modified version of the starter code using when it executes?

    2. When running your modified version of the starter code, how can you tell that the threads are running concurrently?

    3. When does the main method in your modified version of the starter code terminate relative to the other threads?