From Documentation
Jump to: navigation, search
(Thread Creation and Execution)
(Thread Creation and Execution)
Line 5: Line 5:
 
There are two ways to create and start a Java thread. The first involves implementing the Runnable[http://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html] interface and passing an instance to the Thread class constructor.  The second involves extending the Thread[http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html] class it's self, and overriding the provided, yet empty, run method.
 
There are two ways to create and start a Java thread. The first involves implementing the Runnable[http://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html] interface and passing an instance to the Thread class constructor.  The second involves extending the Thread[http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html] class it's self, and overriding the provided, yet empty, run method.
  
 +
<pre>
 
public class HelloRunnable implements Runnable {
 
public class HelloRunnable implements Runnable {
 +
    public void run() {
 +
        System.out.println("Hello from a thread!");
 +
    }
  
<pre>
+
     public static void main(String args[]) {
public void run() {
+
        (new Thread(new HelloRunnable())).start();
     System.out.println("Hello from a thread!");
+
    }
}
+
 
+
public static void main(String args[]) {
+
    (new Thread(new HelloRunnable())).start();
+
 
}
 
}
 
</pre>
 
</pre>

Revision as of 13:53, 11 August 2014

Introduction

This article is a summary of Oracle's java concurrency pages [1]. 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.

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();
    }
}