------------------------------------------------------------------------------
MC logo
Threads in Java
[^] CSc 422 Lecture Slides
------------------------------------------------------------------------------
thrd.java
//
// Simple thread demo in Java.  The main declares a certain amount of
// "resources" (just an integer number) then starts two threads which
// "work through" the resources (mostly by printing that they did).
// The Java thread interface is much cleaner than the standard pthreads
// interface used in C.
//
import java.io.*;
import java.util.*;

public class thrd
{
    static private int depot;           // Shared data.

    // This is the class 
    static class ThrdInfo extends Thread {
        String topr;                    // What to print.
        int low, high;                  // Random range.
        Random rand = new Random();     // Random number generator.

        ThrdInfo(String _topr, int _low, int _high) {
            topr = _topr;
            low = _low;
            high = _high;
        }

        // Get the resource.  (Not the sychnronized keyword.)
        public synchronized int get_resource(int amt)
        {
            if(depot < amt) amt = depot;
            depot -= amt;
            return amt;
        }

        // This is the function run in the thread.
        public void run() 
        {
            while(true) {
                // Choose a random number in range.
                int amt = rand.nextInt(high - low + 1) + low;

                // Remove that amount from the resource depot. 
                amt = get_resource(amt);

                // When the resource is exhausted, we're done. 
                if(amt == 0) return;

                // Do that much "work." 
                while(amt-- > 0) { 
                    System.out.print("["+topr+"]");
                    System.out.flush();
                }
                System.out.println();
                System.out.flush();
            }
        }
    }

    public static void main(String args[]) throws IOException, 
                                                  InterruptedException
    {
        // Create the two thread objects.
        ThrdInfo th1 = new ThrdInfo("Z", 14, 18);
        ThrdInfo th2 = new ThrdInfo("EE", 8, 12);

        // Fill the resource depot and start the the threads running.
        depot = 3000;
        th1.start();
        th2.start();

        // Wait for each of them to be done.
        th1.join();
        System.out.println("First Done"); 
        System.out.flush();
        th2.join();
        System.out.println("Second Done"); 
        System.out.flush();
    }
}