Java Thread: First Steps
(Free Web Tutorials)

by Michael Thomas

Java Thread Home Page

In this tutorial you will discuss Java Thread(s) and do several code-walkthroughs.

Note: On the Java Threads Home page, you can download the whole Java Threads site (all content, tutorials & examples) !!!
In the tutorial download zip file, another zip file containing the java source code is located in the sub directory: \tutorial_firststeps_thread\eclipseprojects\zip

This tutorial covers: Java Threads as of Java 1.6 (last updated 06/30/08)

Prerequisites

Objectives

What is a Java Thread?

A Java Thread is a lightweight process that runs inside of a Java program (process) that has it's own execution context allowing a Java program to do more than one thing at a time (multiple threads running concurrently). From the developers point of view, every Java program has at least one thread called the main thread.

Why use a Java Thread?

Concurrency Concepts

The Thread Object

Implementing the "Runnable" interface

Implementing the "Runnable" interface is the most flexible way to create a thread because you can subclass any desired class.

Sub-classing the Thread Class

Sub-classing the Thread class is not as popular because it is not as flexible as implementing "Runnable" however it is very easy to create.  Implementing "Runnable" is more flexible because you can sub-class any class you desire.

Thread.sleep()

Thread.sleep() causes the current running thread to sleep for a specified time.  After that time, the thread will continue to run when the processor is available.

Thread.interrupt()

Thread.interrupt() is an indication to a thread, by another thread, that it is being requested to do something else.  It is up to the thread being interrupted to decide what it will do, however, termination of the thread is very common.

Thread.interrupt() - busy thread supporting interrupt.

Thread.wait() & Thread.interrupt()

Thread.wait() & Thread.notify()

Thread.join()

Thread.join() allows the current thread to wait for the specified thread (using <ThreadObjectName>.join()) to complete before the current thread continues.  Remember that timing is dependent on the OS.

Synchronizing Threads

This example shows how you can synchronize threads so a thread will wait on another thread to place data into an object before it retrieves that data.

Lab #1

Optional Lab #2

Topics for future Java Thread Tutorials: (Hello World types)