Java. Java language tools for working with threads

Java language tools for working with threads of execution. Thread class. Runnable interface. Main thread of execution. Creating a child thread


Contents


Search other sites:




1. Methods for creating threads of execution

In Java, a thread of execution can be created in one of two ways:

  • by extending the Thread class. This class is the main class on which the Java multithreaded system is built. The Thread class defines one thread of execution. If a program needs to create three threads of execution, then, accordingly, three instances of the Thread class are created;
  • by implementing the Runnable interface. The Runnable interface complements the capabilities of the Thread class.

 

2. Class Thread. Constructors. Review of methods

The Thread class is the main class when working with threads. The creation of any thread begins with the creation of an instance of the Thread class. In this case, you can use the following class constructors

Thread(Runnable threadObject)
Thread(Runnable threadObject, String threadName)

here

  • threadObject – an object of some class that needs to be executed in a thread. This object must implement the Runnable interface (see below) or extend the Thread class;
  • threadName is the name that is set for the created thread of execution. This name can be read by the getName() method.

In general, the code for creating a thread named “My thread” for an object of class MyThreadClass looks like this:

...
// Create the instance of MyThreadClass class
MyThreadClass threadObject = new MyThreadClass();

// Create a child thread on the main thread
Thread thr = new Thread(threadObject, "My thread");
...

The Thread class contains a number of methods for working with threads of execution. Below is the description of these methods in the class:

  • getName() – get the name of the thread of execution;
  • getPriority() – get the priority of the thread of execution;
  • isAlive() – determine if the thread is running;
  • join() – waiting for completion of execution of a thread;
  • run() – specifies the code to be executed in the thread of execution. This is the entry point into the thread;
  • sleep() – suspends the execution of the calling thread for the specified time;
  • start() – starts the thread by calling the run() method.

Examples of using the above methods can be studied here and here.

 

3. Interface Runnable. Features of use

The Runnable interface is used to create a thread of execution. A thread of execution can be created from an object of a class that implements the Runnable interface.
The interface declares one run() method, which has the following general form:

public abstract void run();

The run() method defines the entry point to the thread. As soon as the run() method finishes executing, the thread will also finish executing. In the run() method, you can perform any operations inherent in ordinary methods (declare variables, use classes, call other methods, etc.).

In general, creating a thread of execution for the MyThreadClass class looks like this:

class MyThreadClass implements Runnable {

  // ...

  public void run() {
    // Program code that runs in a thread
    // ...
  }
}

 

4. Main thread of execution. Features. Access to the main thread of execution

After starting the program for execution, one thread starts executing – the main thread of the program. For the main thread, the following characteristic features can be distinguished:

  • the main thread starts executing first;
  • from the main thread you can spawn (create) all child threads;
  • it is desirable that the main thread completes last and does some finishing action when the program closes.

To access the main thread of control, it is necessary to create an instance of the Thread class by calling the static method currentThread(). After that, using the instance, you can use additional functions for controlling the main thread (suspend the main thread, get information about the main thread, etc.).

 

5. An example demonstrating access to the main thread of execution

The example demonstrates access to the main thread in the program and its use.

public class TrainThreads {

  public static void main(String[] args) {

    // Get data about the main thread of execution

    // 1. Get the object of main thread
    Thread thr = Thread.currentThread();

    // 2. Display data about of current thread of execution
    System.out.println("Current thread: " + thr);

    // 3. Set a new name thread of execution
    thr.setName("MY THREAD");

    // 4. Re-display thread data
    System.out.println("Current thread: " + thr);

    // 5. Demonstrate the work of thread of execution
    try {
      for (int n=5; n>0; n--) {
        System.out.println(n);
        Thread.sleep(1000); // stop thread execution for 1 second
      }
    }
    catch (InterruptedException e) {
      System.out.println("The main thread is interrupted.");
    }
  }
}

The result of the program

Current thread: Thread[main,5,main]
Current thread: Thread[MY THREAD,5,main]
5
4
3
2
1

 

6. An example demonstrating creating a child thread by implementing the Runnable interface

One way to create a child thread is to implement the Runnable interface. If the class uses the Runnable interface, then the run() method must be implemented in this class.

// An example of creating a thread using the Runnable interface implementation
// The Runnable interface has a run() method that needs to be implemented
class MyThread implements Runnable {

  Thread thr; // reference to the current thread of execution

  // Class constructor. In the constructor, you need to create a thread
  MyThread() {
    // create a new thread
    thr = new Thread(this, "Thread: MyThread");
    System.out.println("The child thread is created.");
    thr.start(); // run the thread
  }

  // Implementation method run() from Runnable interface
  public void run() {
    try {
      for (int i=10; i>0; i--) {
        System.out.println("Child thread: " + i);
        Thread.sleep(500);
      }
    }
    catch (InterruptedException e) {
      System.out.println("Child thread interrupted.");
    }
    System.out.println("Child thread completed.");
  }
}

public class TrainThreads {

  public static void main(String[] args) {
    // Demonstration of work of a child thread
    new MyThread(); // create a new thread

    try {
      for (int i=10; i>0; i--) {
        System.out.println("Main thread: " + i);
        Thread.sleep(1000);
      }
    }
    catch (InterruptedException e) {
      System.out.println("Main thread interrupted.");
    }
    System.out.println("The main thread is completed.");
  }
}

Program execution result

The child thread is created.
Main thread: 10
Child thread: 10
Child thread: 9
Main thread: 9
Child thread: 8
Child thread: 7
Child thread: 6
Main thread: 8
Child thread: 5
Main thread: 7
Child thread: 4
Child thread: 3
Main thread: 6
Child thread: 2
Child thread: 1
Main thread: 5
Child thread is completed.
Main thread: 4
Main thread: 3
Main thread: 2
Main thread: 1
Main thread is completed.

 

7. An example demonstrating creating a child thread by extending the Thread class

Another way to create a thread is by inheriting (extending) the Thread class. With this method, some methods of the Thread superclass are available. More details on using methods of the Thread class are described here.

// Creating a child thread
class MyThread extends Thread {

  // Constructor
  public MyThread() {
    // create a new thread of execution
    super("Demo thread");
    System.out.println("Child thread is created.");
    start();
  }

  // Implementation of our own run() method,
  // this method specifies the actions (work) that our thread performs
  public void run() {
    try {
      for (int i=10; i>0; i--) {
        System.out.println("Child thread: " + i);
        Thread.sleep(500);
      }
    }
    catch (InterruptedException e) {
      System.out.println("Child thread interrupted.");
    }
    System.out.println("Child thread is completed.");
  }
}

public class TrainThreads {

  public static void main(String[] args) {

    // Thread creation demonstration
    new MyThread(); // create a new child thread

    try {
      for (int i=10; i>0; i--) {
        System.out.println("Main thread: " + i);
        Thread.sleep(1000);
      }
    }
    catch (InterruptedException e) {
      System.out.println("Main thread interrupted:");
    }
    System.out.println("Main thread is completed.");
  }
}

The result of the program

Child thread is created.
Child thread: 10
Main thread: 10
Child thread: 9
Main thread: 9
Child thread: 8
Child thread: 7
Child thread: 6
Main thread: 8
Child thread: 5
Child thread: 4
Main thread: 7
Child thread: 3
Child thread: 2
Main thread: 6
Child thread: 1
Main thread: 5
Child thread is completed.
Main thread: 4
Main thread: 3
Main thread: 2
Main thread: 1
Main thread is completed.

 


Related topics