Threads 1

Nicholas Duchon: Apr 5, 2017

Key Concepts:


Other places:

I am putting together some web pages on threads and how to control them. See:


Showing current threads:

This code:

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.BorderLayout;

public class HelloND extends JPanel {
  public static final long serialVersionUID = 123; // ND: junk
  int count = 0;
  Thread ta [] = new Thread [20];
 
  public HelloND (String name) {
    setBackground (Color.cyan);

    JFrame jf = new JFrame ();
    jf.setLocationRelativeTo (null);
    jf.setTitle (name);
    jf.setSize (400, 200);
    jf.add (this, BorderLayout.CENTER);
    jf.setVisible (true);
    jf.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
  } // end constructor
 
  public void paint (Graphics g) {
    super.paint (g);
    g.drawString ("Hello, Nick " + count++, 10, 50);
    int m = Thread.enumerate (ta);
    System.out.println ();
    for (int i = 0; i < m; i++)
      System.out.println (ta[i].toString());
 
} // end method paintComponent
 
  public static void main (String args []) {
    new HelloND ("This is a test");
    java.util.Scanner s = new java.util.Scanner (System.in);
    while (! s.next().equals ("q")) System.out.println ("q to quit");
    System.out.println ("--- bye ---");
 
} // end main
} // end class HelloND


3 Examples:

I have attached links to 3 programs developed by Dr. Kann to demonstrate basic features of threads and the Runable interface. I will eventually comment these codes, but I think there are some comments about them in the course modules.

Bounded Buffer

Threads and concurrency - Bounded Buffer example

The attached example is a modification of code developed by Chuck Kann for his text, Creating Components: Object Oriented, Concurrent, and Distributed Computing in Java, Auerbach Publications, 2004, pp 67-94.

It demonstrates the following:

Code - BoundedBuffer.java

// File: BoundedBuffer.java
// Author: Chuck Kann with modifications by Nicholas Duchon
// Date: Nov 17, 2010
// Purpose: demonstrate synchronization using a bounded buffer
// Notes:
//   Classes:
//     BoundedBuffer as a circular array
//       BoundedBuffer (int size)
//       put           (int value)
//       get           ()          : int
//       main          (String [])
//     Producer
//       Producer      (BoundedBuffer)
//       run           ()
//     Consumer
//       Consumer      (BoundedBuffer)
//       run           ()
//   Event/state table:
//                        put      get
//             EMPTY     OPEN     wait
//     OPEN,1<size<N-1   OPEN     OPEN
//     OPEN,size=1       OPEN     EMPTY
//     OPEN,size=N-1     FULL     OPEN
//             FULL      wait     OPEN

public class BoundedBuffer {
  static int BUFFER_SIZE = 3;
  static int RUN_COUNT   = 20;
 
  enum State {EMPTY, OPEN, FULL};
 
  int values [];
  int first = 0, last = 0, count = 0;
  State bufferState = State.EMPTY;

  public BoundedBuffer (int pSize) {
    values = new int [pSize];
 
} // end int constructor
 
  public synchronized void put (int value) {
    // Pre-condition:
    while (bufferState == State.FULL)
      try {
        // wait releases locks, notify reasserts locks before continuing
        // notify comes from get method
        wait ();
      } catch (InterruptedException e) {}

    System.out.println (" +++ Buffer adding: " + value);
    values [last] = value;
    last = (++last) % values.length;
    count++;

    // post-condition
    if (count >= values.length) bufferState = State.FULL;
    else bufferState = State.OPEN;

    notifyAll (); // notifies the get method
 
} // end method add
 
  public synchronized int get () {
    // pre-condition
    while (bufferState == State.EMPTY)
      try {
        // again, wait releases locks until notify
        // notify must come from add method
        wait ();
      } catch (InterruptedException e) {}

    int value = values[first];
    System.out.println (" --- Buffer returning: " + value);
    first = (++first) % values.length;
    count--;
   
    // post-condition
    if (count <= 0) bufferState = State.EMPTY;
    else bufferState = State.OPEN;

    notifyAll (); // notifies the add method
   
    return value;
 
} // end method get
 
  public static void main (String args []) {
    BoundedBuffer bb = new BoundedBuffer (BUFFER_SIZE);
    Thread tp = new Thread (new Producer (bb));
    Thread tc = new Thread (new Consumer (bb));
    tp.start();
    tc.start();
 
} // end main
} // end class BoundedBuffer

class Producer implements Runnable {
  BoundedBuffer bb;
 
  public Producer (BoundedBuffer x) {bb = x;}
 
  // executes runCount add's
  public void run () {
    System.out.println ("Produceer starting");
    for (int i = 0; i < BoundedBuffer.RUN_COUNT; i++) {
      System.out.println ("+Producer inserting value: " + i);
      bb.put (i);
    } // end for i, production count
 
} // end method run
} // end class Producer

class Consumer implements Runnable {
  BoundedBuffer bb;
 
  public Consumer (BoundedBuffer x) {bb = x;}
 
  // executes runCount get's
  public void run () {
    System.out.println ("Consumer Starting");
    for (int i = 0; i < BoundedBuffer.RUN_COUNT; i++)
      System.out.println ("-Consumer got value: " + bb.get());
  } // end method run
} // end class Producer


ND.