From Documentation
Revision as of 13:58, 11 August 2014 by Edward (Talk | contribs) (Introduction)

Jump to: navigation, search

Introduction

This first half of this article is a summary of Oracle's java concurrency pages [1], while the second half will serve as a repository for Java Thread code examples. Java was designed from the bottom up to support threaded programming, and shares a number of concepts with the C language threaded paradigm PThreads. This article assumes a familiarity with the concept of threads, as well as a functional understanding of the Java programming language. Before continueing please review the specifics of working with OPENJDK on Sharcnet. All of the examples provided have been tested on Sharcnet, specifically on the Orca development nodes.

I have started this article as opposed to just forwarding to Oracles page so that I will be able to post answers to common questions here, or linked to here. On that note, feel free to update this page with your experiences/tips, and forward any bugs, questions, or problems to Ed Armstrong (edward@sharcnet.ca), or submit a ticket in the SHARCNET problem tracking system.

Thread Creation and Execution

There are two ways to create and start a Java thread. The first involves implementing the Runnable[2] interface and passing an instance to the Thread class constructor. The second involves extending the Thread[3] class it's self, and overriding the provided, yet empty, run method.

public class HelloRunnable implements Runnable {
    public void run() {
        System.out.println("Hello from a thread!");
    }

    public static void main(String args[]) {
        (new Thread(new HelloRunnable())).start();
    }
}
public class HelloThread extends Thread {
    public void run() {
        System.out.println("Hello from a thread!");
    }

    public static void main(String args[]) {
        (new HelloThread()).start();
    }
}