Java Threads

Easy Java Threads tutorial – part 1

Keywords: Concurrency, Java Multithreading, Threads

Multithreading is an essential feature of Java. In this tutorial I will focus on explaining the basics of Java Threads, how to use them and how to feel comfortable with them. You will find lots of examples focused on single feature or method. Learning through examples is usually the best way to understand programming languages. For running these examples you can use an IDE like Eclispe or Netbeans, and if you don’t like to install them you can search for an online Java IDE.

What is Java thread?

Threads are lightweight processes used by Java to support concurrency. All Java programs has at least one thread – the main thread, created by the JVM at the start of the program and executing the content of the main method. Every Java thread is created and managed by Thread class.

How to create threads in Java?

Each thread is associated with an instance of Thread. You can create threads in two different ways

  • With Thread instance
  • Separating the thread logic from its management

Here are two very basic examples of the two different approaches – create another thread:

First I will subclass Thread

public class EasyThread extends Thread {

    public void run() {
        System.out.println("We have another thread!");
    }

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

}

And the next one will implements Runnable. At the end you again need to create a thread instance and pass the Runnable object to it.

public class ExampleRunnable implements Runnable {

    public void run() {
        System.out.println("We have another thread but we are in Runnable!");
    }

    public static void main(String args[]) {
      	ExampleRunnable runnable = new ExampleRunnable();
    	Thread thread = new Thread(runnable);
      	thread.start();        
    }

}

How to manage a thread

Sleep – its time to sleep

The sleep method is used to suspend the current thread execution for a fixed amount of time and its used to make execution time available for other threads. Keep in mind that sleep time is not precise because it relies on the OS running on this device. So you can’t be sure if the thread will sleep the given time period precisely – and this question is often used in Java tests, especially job tests.
Also keep in mind that the method sleep throws InterruptedException and you must state that your method throws it or you need to add a try-catch block.
Example of using Thread.sleep:

public class EasyThread extends Thread {

    public void run() {
        System.out.println("We have another thread!");
      	try {
      		sleep(2000);
        } catch (InterruptedException e) {}
      	System.out.println("I like to sleep");
    }

    public static void main(String args[]) throws InterruptedException {
    	EasyThread easyThread = new EasyThread();	    
        easyThread.start();
        sleep(2000);
      	System.out.println("Buy from main thread");
    }

}

And the result of the code above:
We have another thread!
Buy from main thread
I like to sleep

Join (join the dark side) or at least Thread.join

This method allows one thread to wait for the completion of another. The current thread pauses and the thread which join method is called takes over. You can specify a time period but again like sleep the time period is not precise and depends on the OS.
Here is the same example with join:

public class EasyThread extends Thread {

    public void run() {
        System.out.println("We have another thread!");
      	try {
      		sleep(2000);
        } catch (InterruptedException e) {}
      	System.out.println("I like to sleep");
    }

    public static void main(String args[]) throws InterruptedException {
    	EasyThread easyThread = new EasyThread();	    
        easyThread.start();
        easyThread.join();
      	System.out.println("Buy from main thread");
    }

}

This will be the end of part one. Part two will look at synchronization and a bit of more complex topics about Java Threads.

Leave a Reply

Your email address will not be published. Required fields are marked *