Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java Thread Join Example

farenda 2015-10-30 0

Problem:

How to Java Thread join to do simple synchronization of threads? In this post we show an example where one thread waits for another to clean up after it. Read on!

Solution:

When a couple of threads have to do work sequentially we can guarantee their order in a few ways. One way could be to use Single Thread Executor that can serialize threads. In the below example we’re going to show how to do that using Thread.join() method, which is sufficient for simple cases.

The Thread.join() method when called from one thread, stops it, and waits for the other thread to die. In the example we have a BusyJob thread that we want to run first and a JobCleaner thread that we want to run after the busy job has finished. In the main thread we start JobCleaner thread, which will start BusyJob thread – both threads could be started from the main thread, but we implemented it this way. Also in main thread we are waiting for the cleaner to finish and then we end the program.

package com.farenda.java.lang;

import java.util.concurrent.TimeUnit;

public class ThreadJoinExample {

    private static class BusyJob extends Thread {
        @Override
        public void run() {
            System.out.println("Started BusyJob...");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                // ignore
            }
            System.out.println("Busy job done.");
        }
    }

    private static class JobCleaner extends Thread {

        private Thread job;

        public JobCleaner(Thread job) {
            this.job = job;
        }

        @Override
        public void run() {
            job.start();
            System.out.println("Cleaner is waiting on a busy job...");
            try {
                job.join();
                System.out.println("Cleaning up after job: "
                                   + job.getClass().getSimpleName());
            } catch (InterruptedException e) {
                System.out.println("Some other thread has interrupted me!");
            }
            System.out.println("Cleaning done.");
        }
    }

    public static void main(String[] args) {
        Thread busyJob = new BusyJob();
        Thread cleaner = new JobCleaner(busyJob);

        System.out.println("Starting the cleaner.");
        cleaner.start();

        System.out.println(Thread.currentThread().getName()
                + " is waiting for the cleaner to finish");
        try {
            cleaner.join();
        } catch (InterruptedException e) {
            System.out.println("main thread interrupted!");
        }

        System.out.println("End of main thread!");
    }
}

The join method has three variants:

  • void join()
    It’s the same as join(0)
  • void join(long millis)
    It waits for given number of milliseconds for this thread to die.
  • void join(long millis, int nanos)
    It waits for given number of milliseconds plus nanoseconds for this thread to die.

And here’s the result of running the above example:

Starting the cleaner.
main is waiting for the cleaner to finish
Cleaner is waiting on a busy job...
Started BusyJob...
Busy job done.
Cleaning up after job: BusyJob
Cleaning done.
End of main thread!

As you can see all threads have executed in order as expected. This method of serialization is fine for simple cases like this one, but for more threads it may get complicated very fast and then better use Single Thread Executor.

Share with the World!
Categories Java Tags java, java-concurrency
Previous: Java UncaughtExceptionHandler with ExecutorService
Next: Java Thread pause

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored