Skip to content Skip to sidebar Skip to footer

How to Start a Thread Again

Jakob Jenkov
Last update: 2021-03-09

A Java Thread is like a virtual CPU that can execute your Coffee code - inside your Java application. when a Java application is started its chief() method is executed past the main thread - a special thread that is created by the Java VM to run your awarding. From inside your application you can create and start more than threads which tin execute parts of your application code in parallel with the main thread.

Java threads are objects like any other Java objects. Threads are instances of class coffee.lang.Thread, or instances of subclasses of this class. In addition to being objects, java threads can as well execute code. In this Java thread tutorial I will explain how to create and start threads.

Java Threads Video Tutorial

In case you prefer video, hither is a video version of this Java Threads tutorial.

Java Threads Tutorial

Creating and Starting Threads

Creating a thread in Java is done like this:

          Thread thread = new Thread();        

To start the Java thread you will call its offset() method, similar this:

          thread.offset();        

This case doesn't specify any code for the thread to execute. Therfore the thread volition cease again right abroad subsequently it is started.

There are ii ways to specify what code the thread should execute. The starting time is to create a subclass of Thread and override the run() method. The 2nd method is to pass an object that implements Runnable (java.lang.Runnable to the Thread constructor. Both methods are covered below.

Thread Subclass

The starting time way to specify what code a thread is to run, is to create a bracket of Thread and override the run() method. The run() method is what is executed by the thread after you call commencement(). Here is an example of creating a Java Thread subclass:

          public class MyThread extends Thread {      public void run(){        System.out.println("MyThread running");     }   }        

To create and start the above thread y'all can do like this:

          MyThread myThread = new MyThread();   myTread.outset();        

The start() call will return as soon as the thread is started. Information technology volition not wait until the run() method is done. The run() method volition execute as if executed by a dissimilar CPU. When the run() method executes it will print out the text "MyThread running".

You tin can as well create an anonymous subclass of Thread like this:

          Thread thread = new Thread(){     public void run(){       Organization.out.println("Thread Running");     }   }    thread.beginning();        

This example will print out the text "Thread running" once the run() method is executed by the new thread.

Runnable Interface Implementation

The second manner to specify what code a thread should run is by creating a class that implements the java.lang.Runnable interface. A Java object that implements the Runnable interface tin exist executed by a Coffee Thread. How that is washed is shown a bit later in this tutorial.

The Runnable interface is a standard Java Interface that comes with the Coffee platform. The Runnable interface but has a unmarried method run(). Here is basically how the Runnable interface looks:

public interface Runnable() {      public void run();  }        

Whatever the thread is supposed to do when it executes must exist included in the implementation of the run() method. There are iii means to implement the Runnable interface:

  1. Create a Java class that implements the Runnable interface.
  2. Create an bearding grade that implements the Runnable interface.
  3. Create a Java Lambda that implements the Runnable interface.

All 3 options are explained in the following sections.

Coffee Class Implements Runnable

The kickoff style to implement the Java Runnable interface is by creating your own Coffee class that implements the Runnable interface. Hither is an example of a custom Java class that implements the Runnable interface:

          public course MyRunnable implements Runnable {      public void run(){        System.out.println("MyRunnable running");     }   }        

All this Runnable implementation does is to print out the text MyRunnable running. After printing that text, the run() method exits, and the thread running the run() method will end.

Bearding Implementation of Runnable

You can also create an anonymous implementation of Runnable. Hither is an example of an anonymous Java class that implements the Runnable interface:

Runnable myRunnable =     new Runnable(){         public void run(){             System.out.println("Runnable running");         }     }        

Autonomously from being an anononymous class, this example is quite similar to the instance that used a custom class to implement the Runnable interface.

Java Lambda Implementation of Runnable

The tertiary manner to implement the Runnable interface is by creating a Java Lambda implementation of the Runnable interface. This is possible because the Runnable interface only has a unmarried unimplemented method, and is therefore practically (although possibly unintentionally) a functional Java interface.

Here is an example of a Coffee lambda expression that implements the Runnable interface:

Runnable runnable =         () -> { System.out.println("Lambda Runnable running"); };        

Starting a Thread With a Runnable

To have the run() method executed by a thread, pass an case of a class, bearding class or lambda expression that implements the Runnable interface to a Thread in its constructor. Hither is how that is done:

Runnable runnable = new MyRunnable(); // or an bearding class, or lambda...  Thread thread = new Thread(runnable); thread.start();        

When the thread is started it will call the run() method of the MyRunnable instance instead of executing it'south own run() method. The to a higher place example would print out the text "MyRunnable running".

Bracket or Runnable?

In that location are no rules near which of the two methods that is the best. Both methods works. Personally though, I prefer implementing Runnable, and handing an example of the implementation to a Thread case. When having the Runnable's executed past a thread puddle it is easy to queue up the Runnable instances until a thread from the puddle is idle. This is a little harder to do with Thread subclasses.

Sometimes you may accept to implement Runnable as well as subclass Thread. For instance, if creating a subclass of Thread that can execute more than than one Runnable. This is typically the case when implementing a thread puddle.

Common Pitfall: Calling run() Instead of start()

When creating and starting a thread a common fault is to call the run() method of the Thread instead of start(), like this:

          Thread newThread = new Thread(MyRunnable());   newThread.run();  //should be commencement();        

At start you lot may not notice anything considering the Runnable's run() method is executed like you expected. Even so, information technology is Non executed by the new thread you just created. Instead the run() method is executed by the thread that created the thread. In other words, the thread that executed the in a higher place 2 lines of code. To have the run() method of the MyRunnable instance called by the new created thread, newThread, you MUST phone call the newThread.beginning() method.

Thread Names

When you create a Coffee thread you lot can give information technology a name. The name can help yous distinguish different threads from each other. For instance, if multiple threads write to System.out it can exist handy to see which thread wrote the text. Here is an example:

          Thread thread = new Thread("New Thread") {       public void run(){         System.out.println("run by: " + getName());       }    };      thread.starting time();    System.out.println(thread.getName());        

Notice the string "New Thread" passed as parameter to the Thread constructor. This string is the name of the thread. The name can be obtained via the Thread'due south getName() method. You lot tin too laissez passer a name to a Thread when using a Runnable implementation. Here is how that looks:

          MyRunnable runnable = new MyRunnable();    Thread thread = new Thread(runnable, "New Thread");     thread.start();    System.out.println(thread.getName());        

Notice however, that since the MyRunnable class is non a subclass of Thread, information technology does not accept access to the getName() method of the thread executing it.

Thread.currentThread()

The Thread.currentThread() method returns a reference to the Thread case executing currentThread() . This way you lot tin get access to the Coffee Thread object representing the thread executing a given block of code. Here is an example of how to use Thread.currentThread() :

Thread thread = Thread.currentThread();        

Once you lot take a reference to the Thread object, you lot can call methods on information technology. For instance, yous can get the proper name of the thread currently executing the code like this:

          String threadName = Thread.currentThread().getName();        

Java Thread Instance

Here is a small case. First it prints out the name of the thread executing the main() method. This thread is assigned by the JVM. Then information technology starts up 10 threads and give them all a number equally name ("" + i). Each thread and so prints its name out, then stops executing.

public class ThreadExample {    public static void main(String[] args){     System.out.println(Thread.currentThread().getName());     for(int i=0; i<10; i++){       new Thread("" + i){         public void run(){           System.out.println("Thread: " + getName() + " running");         }       }.outset();     }   } }        

Note that even if the threads are started in sequence (1, ii, 3 etc.) they may not execute sequentially, pregnant thread 1 may not be the beginning thread to write its name to Organisation.out. This is considering the threads are in principle executing in parallel and non sequentially. The JVM and/or operating system determines the order in which the threads are executed. This society does not accept to be the same order in which they were started.

Suspension a Thread

A thread can pause itself past calling the static method Thread.sleep() . The slumber() takes a number of milliseconds every bit parameter. The sleep() method will attempt to sleep that number of milliseconds before resuming execution. The Thread sleep() is not 100% precise, just information technology is pretty skilful withal. Hither is an example of pausing a Java thread for iii seconds (3.000 millliseconds) by calling the Thread sleep() method:

try {     Thread.sleep(10L * 1000L); } catch (InterruptedException e) {     eastward.printStackTrace(); }        

The thread executing the Java lawmaking above, will sleep for approximately 10 seconds (10.000 milliseconds).

Terminate a Thread

Stopping a Java Thread requires some grooming of your thread implementation code. The Coffee Thread form contains a stop() method, but it is deprecated. The original stop() method would not provide any guarantees about in what state the thread was stopped. That means, that all Java objects the thread had access to during execution would exist left in an unknown state. If other threads in your application also has access to the aforementioned objects, your awarding could fail unexpectedly and unpredictably.

Instead of calling the stop() method you volition have to implement your thread code and so it tin can be stopped. Here is an example of a class that implements Runnable which contains an extra method chosen doStop() which signals to the Runnable to stop. The Runnable will check this signal and cease when it is ready to do so.

public class MyRunnable implements Runnable {      private boolean doStop = simulated;      public synchronized void doStop() {         this.doStop = true;     }      private synchronized boolean keepRunning() {         return this.doStop == false;     }      @Override     public void run() {         while(keepRunning()) {             // keep doing what this thread should do.             System.out.println("Running");              endeavour {                 Thread.slumber(3L * 1000L);             } catch (InterruptedException e) {                 eastward.printStackTrace();             }          }     } }        

Find the doStop() and keepRunning() methods. The doStop() is intended to be called from some other thread than the thread executing the MyRunnable'southward run() method. The keepRunning() method is called internally by the thread executing the MyRunnable'southward run() method. As long as doStop() has not been chosen the keepRunning() method volition return true - meaning the thread executing the run() method will go along running.

Here is an example of starting a Coffee thread that executes an example of the above MyRunnable class, and stopping it over again afterwards a delay:

public class MyRunnableMain {      public static void primary(String[] args) {         MyRunnable myRunnable = new MyRunnable();          Thread thread = new Thread(myRunnable);          thread.start();          try {             Thread.slumber(10L * 1000L);         } grab (InterruptedException e) {             eastward.printStackTrace();         }          myRunnable.doStop();     } }        

This example start creates a MyRunnable instance, then passes that example to a thread and starts the thread. Then the thread executing the primary() method (the main thread) sleeps for 10 seconds, and and then calls the doStop() method of the MyRunnable instance. This volition crusade the thread executing the MyRunnable method to stop, because the keepRunning() will return false after doStop() has been called.

Please keep in listen that if your Runnable implementation needs more than just the run() method (due east.1000. a stop() or pause() method too), and so y'all tin can no longer create your Runnable implementation with a Java lambda expression. A Java lambda can only implement a single method. Instead you must apply a custom grade, or a custom interface that extends Runnable which has the extra methods, and which is implemented by an anonymous form.

cooksement1988.blogspot.com

Source: http://tutorials.jenkov.com/java-concurrency/creating-and-starting-threads.html

Postar um comentário for "How to Start a Thread Again"