From Documentation
Jump to: navigation, search
(Thread.join())
(Thread.join())
Line 94: Line 94:
  
 
==Thread.join()==
 
==Thread.join()==
Calling join causes the calling thread to wait until the target thread terminates.  This is in effect a [[#Glossary of terms | barrier]] that both the calling thread and the target thread must reach before execution continues.
+
Calling join causes the calling thread to wait until the target thread terminates.  This is in effect a [[Glossary of terms | barrier]] that both the calling thread and the target thread must reach before execution continues.
 
The following code is an example of two threads running (the main execution thread and a spawned thread) both counting up to 10.  Note that only one thread can access System.out at a time.
 
The following code is an example of two threads running (the main execution thread and a spawned thread) both counting up to 10.  Note that only one thread can access System.out at a time.
  

Revision as of 09:36, 14 August 2014

Introduction

The Java threads instructions and example will be laid out over two articles. This first article is a summary of Oracle's java concurrency pages [1], while the second article 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 the Oracle 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.

Oracle Copyright Notice

The following is the Oracle license agreement, which applies to the code samples in this article.

Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
  - Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
  - Neither the name of Oracle or the names of its
    contributors may be used to endorse or promote products derived
    from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Thread Creation, Execution, and Control

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.

Runnable code example ©

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

Thread code example ©

public class HelloThread extends Thread {
    public void run() {
        System.out.println("Hello from a thread!");
    }

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

Thread.sleep()

The Thread.sleep() method causes a thread to suspend execution for a defined amount of time. The time given is not exact and may be more or less, it is best thought of as a "suggested" amount of time.

SleepMessages.java code example ©

public class SleepMessages {
    public static void main(String args[])
        throws InterruptedException {
        String importantInfo[] = {
            "Mares eat oats",
            "Does eat oats",
            "Little lambs eat ivy",
            "A kid will eat ivy too"
        };

        for (int i = 0;
             i < importantInfo.length;
             i++) {
            //Pause for 4 seconds
            Thread.sleep(4000);
            //Print a message
            System.out.println(importantInfo[i]);
        }
    }
}

You will notice in the above code example, the "throw InterruptedException". This is indicative of the fact that threads can be interrupted, and it is up to the programmer to decide on the threads behavior. The most basic, and most often used case, is to cause a threads early termination.

<TODO: provide a code example; I don't like Oracles in this case>

Thread.join()

Calling join causes the calling thread to wait until the target thread terminates. This is in effect a barrier that both the calling thread and the target thread must reach before execution continues. The following code is an example of two threads running (the main execution thread and a spawned thread) both counting up to 10. Note that only one thread can access System.out at a time.

  1. public class MyRunnable implements Runnable{
  2.     private final String name;
  3.  
  4.     MyRunnable(String name) {
  5.         this.name = name;
  6.     }
  7.     @Override
  8.     public void run() {
  9.         for (int i = 0; i < 10; i++){
  10.             System.out.println(name + " " + i);
  11.         }
  12.     }
  13.  
  14.     public static void main(String[] args) {
  15.         MyRunnable r1 = new MyRunnable("r1");
  16.         MyRunnable r2 = new MyRunnable("r2");
  17.  
  18.         Thread t1 = new Thread(r1);
  19.         t1.start();
  20.         r2.run();
  21.     }
  22. }

This produces the following output. Thread r2 starts printing out, then thread r1, followed again by thread r2.

r2 0
r2 1
r1 0
r1 1
r1 2
r1 3
r1 4
r1 5
r1 6
r1 7
r1 8
r1 9
r2 2
r2 3
r2 4
r2 5
r2 6
r2 7
r2 8
r2 9

We now add Thread.join between lines 19 and 20; note that we also add "throws InterruptedException" to main because the thread that calls join is waiting, and thus can be interrupted.

  1. public class MyRunnable implements Runnable{
  2.     private final String name;
  3.  
  4.     MyRunnable(String name) {
  5.         this.name = name;
  6.     }
  7.     @Override
  8.     public void run() {
  9.         for (int i = 0; i < 10; i++){
  10.             System.out.println(name + " " + i);
  11.         }
  12.     }
  13.  
  14.     public static void main(String[] args) throws InterruptedException {
  15.         MyRunnable r1 = new MyRunnable("r1");
  16.         MyRunnable r2 = new MyRunnable("r2");
  17.  
  18.         Thread t1 = new Thread(r1);
  19.         t1.start();
  20.         t1.join();
  21.         r2.run();
  22.     }
  23. }

This gives the following output where thread r1 completes before thread r2 calls its run method.

r1 0
r1 1
r1 2
r1 3
r1 4
r1 5
r1 6
r1 7
r1 8
r1 9
r2 0
r2 1
r2 2
r2 3
r2 4
r2 5
r2 6
r2 7
r2 8
r2 9