Java Threads

This talk summarizes material from

1 What are Threads?

2 Timer: Avoiding Threads

import java.util.Timer;
import java.util.TimerTask;

/**
 * Simple demo that uses java.util.Timer to schedule a task to execute
 * once 5 seconds have passed.
 */

public class Reminder {
  Timer timer;
  
  public Reminder(int seconds) {
    timer = new Timer();
    timer.schedule(new RemindTask(), seconds*1000);
  }

  class RemindTask extends TimerTask {
    public void run() {
      System.out.println("Time's up!");
      timer.cancel(); //Terminate the timer thread
    }
  }

  public static void main(String args[]) {
    System.out.println("About to schedule task.");
    new Reminder(5);
    System.out.println("Task scheduled.");
  }
}

//To schedule it to go off every second do:
timer.schedule(new RemindTask(), seconds*1000, 1*1000);

3 Extending Thread

public class SimpleThread extends Thread {
  public SimpleThread(String str) {
    super(str); //sets the name of this thread to str.
  }
  public void run() {
    for (int i = 0; i < 10; i++) {
      //print i and the name of this thread.
      System.out.println(i + " " + getName());
      try {
        sleep((long)(Math.random() * 1000));
      } catch (InterruptedException e) {}
    }
    System.out.println("DONE! " + getName());
  }
}

public class TwoThreadsDemo {
  public static void main (String[] args) {
    new SimpleThread("Jamaica").start();
    new SimpleThread("Fiji").start();
  }
}

4 Implementing Runnable Interface

import java.awt.Graphics;
import java.awt.Color;
import java.util.*;
import java.text.DateFormat;

public class Clock extends java.applet.Applet implements Runnable {
  private Thread clockThread = null;

  //Applet method
  public void init() {
    setBackground(Color.white);
  }

  //Applet method
  public void start() {
    if (clockThread == null) {
      clockThread = new Thread(this, "Clock");
      clockThread.start(); //thread starts running
    }
  }

  //A Thread method.
  public void run() {
    Thread myThread = Thread.currentThread();
    while (clockThread == myThread) {
      repaint(); //causes paint() to be called
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e){ }
    }
  }

  //An applet method.
  public void paint(Graphics g) {
    Calendar cal = Calendar.getInstance();
    Date date = cal.getTime();
    DateFormat dateFormatter = DateFormat.getTimeInstance();
    g.drawString(dateFormatter.format(date), 5, 10);
  }
  // overrides Applet's stop method, not Thread's
  public void stop() {
    clockThread = null;
  }
}

5 Lifecycle

6 Priority

7 Synchronize

public class CubbyHole {
  private int contents;
  private boolean available = false;

  public synchronized int get() {
    while (available == false) {
      try {
        wait();
      } catch (InterruptedException e) { }
    }
    available = false;
    notifyAll();
    return contents;
  }

  public synchronized void put(int value) {
    while (available == true) {
      try {
        wait();
      } catch (InterruptedException e) { }
    }
    contents = value;
    available = true;
    notifyAll();
  }
}

public class ProducerConsumerTest {
  public static void main(String[] args) {
    CubbyHole c = new CubbyHole();
    Producer p1 = new Producer(c, 1);
    Consumer c1 = new Consumer(c, 1);

    p1.start();
    c1.start();
  }
}

8 Grouping

public class EnumerateTest {
  public void listCurrentThreads() {
    ThreadGroup currentGroup =
      Thread.currentThread().getThreadGroup();
    int numThreads = currentGroup.activeCount();
    Thread[] listOfThreads = new Thread[numThreads];

    currentGroup.enumerate(listOfThreads);
    for (int i = 0; i < numThreads; i++)
      System.out.println("Thread #" + i + " = " + 
                         listOfThreads[i].getName());
  }
}

URLs

  1. Java Network Programming, http://www.amazon.com/exec/obidos/ASIN/1565928709/multiagentcom/
  2. Doing Two or More Tasks At Once, http://java.sun.com/docs/books/tutorial/essential/threads/

This talk available at http://jmvidal.cse.sc.edu/talks/javathreads/
Copyright © 2009 José M. Vidal . All rights reserved.

28 May 2002, 08:35AM