Java. Threads of execution. Methods of the Thread class

Threads of execution. Methods of the Thread class: getName(), run(), start(), sleep(). Examples

Before studying this topic, it is recommended that you familiarize yourself with the following topic:


Contents


Search other websites:




1. The getName() method. Get stream name. Example

An example of determining the name of the main thread and child thread. The child thread is implemented in the MyThread class, which contains the following members:

  • internal field thr, which is a reference to the Thread class;
  • constructor MyThread(String). The constructor receives as an input parameter the name of the created thread, which is launched for execution;
  • run() method. In this method, it programmed some work performed by the thread;
  • getNameThread() method – returns the name of the created thread by calling the getName() method.

 

// The class that encapsulates the thread of execution
class MyThread implements Runnable {

  Thread thr; // reference to the current thread

  // Class constructor MyThread - receives the thread name
  MyThread(String name) {
    // Create an instance of thr and set the stream name to it
    thr = new Thread(this, name);

    // Start the thread for execution
    thr.start(); // the run() method is called
  }

  // The entry point into the stream is the run() method
  public void run() {
    // do some work on the thread
    System.out.println("MyThread.run() - begin");

    for (int i=0; i<200; i++) {
      try {
        Thread.sleep(5);
      }
      catch (InterruptedException e) {
        System.out.println(e.getMessage());
      }
    }

    System.out.println("MyThread.run() - end");
  }

  // Method that returns the name of the thr thread
  String getNameThread() {
    // Invoke getName() method of Thread class
    return thr.getName();
  }
}

public class Threads {

  public static void main(String[] args) {
    // Method getName() - get the name of thread.
    // 1. Get the name of the main thread and display it
    Thread mainThread = Thread.currentThread();
    String name = mainThread.getName(); // name = "main"
    System.out.println("name of main Thread = " + name);

    // 2. Get the name of the child thread
    // 2.1. Create a child thread and give it a name
    MyThread t1 = new MyThread("Thread-1");

    // 2.2. Print the name of the child thread to control
    System.out.println(t1.getNameThread());
  }
}

Program result

name of main Thread = main
Thread-1
MyThread.run() - begin
MyThread.run() - end

 

2. Methods run(), start(). Starting and executing a thread. Example

The start() and run() methods are used when starting and executing a thread. The start() method is used to indicate that the thread should be started. In its code, the start() method calls the run() method.

The general form of the start() method is as follows:

public void start()

The run() method specifies the code to run on the thread. The run() method is the entry point to the stream. The run() method is declared in the Runnable interface. In order to encapsulate the thread of execution in the class, you need to implement the Runnable interface and override the run() method according to the example below

class MyThreadClass implements Runnable {

  // ...

  void run() {
    // thread code
    // ...
  }
}

The run() method code starts executing only after the start() method is called. The general form of the run() method is as follows:

void run()

Example. The example demonstrates various ways to start and create a thread. These methods use the start() and run() methods of the Thread class.

// Creating a thread using the inheritance method of the Thread class
class MyThread1 extends Thread {

  // Method that starts execution of the thread
  public void startThread1() {
    // The method calls the start() method of the Thread class to start the thread
    // 1. Create a stream by giving it its own instance
    Thread thr = new Thread(this, "MyThread1");

    // 2. Start the stream
    thr.start(); // Invoke the run() method
  }

  // Method run()
  public void run() {
    // Display a message about the start of thread execution
    System.out.println("MyThread1.run() - begin");

    try {
      Thread.sleep(500);

      // do some work on the thread
      for (int i=0; i<10000; i++);

    } 
    catch (InterruptedException e) {
      e.getMessage();
    }

    // Display a message about the end of the thread execution
    System.out.println("MyThread1.run() - end");
  }
}

// Creating a thread using the implementation of Runnable interface
class MyThread2 implements Runnable {

  // Method that starts execution of the thread
  public void startThread2() {
    // The method calls the start() method of the Thread class to start the thread
    // 1. Create a thread by specifying its own instance
    Thread thr = new Thread(this, "MyThread1");

    // 2. Run the thread
    thr.start(); // The run() method is called
  }

  // Method run() - the execution of thread
  public void run() {
    // Display a message about the start of thread execution
    System.out.println("MyThread2.run() - begin");

    try {
      Thread.sleep(500);

      // do some work on the thread
      for (int i=0; i<10000; i++);

    } 
    catch (InterruptedException e) {
      e.getMessage();
    }

    // Display a message about the end of the thread execution
    System.out.println("MyThread2.run() - end");
  }
}

public class Threads {

  public static void main(String[] args) {
    // Demonstration of start() and run() methods
    // 1. Declare the instances of MyThread1 and MyThread2 classes
    MyThread1 mt1 = new MyThread1();
    MyThread2 mt2 = new MyThread2();

    // 2. Run threads to execution
    mt1.startThread1();
    mt2.startThread2();
  }
}

The result of the program

MyThread1.run() - begin
MyThread2.run() - begin
MyThread1.run() - end
MyThread2.run() - end

 

3. Method sleep(). Delay in thread execution. Example

The sleep() method is used to specify the delay in milliseconds in the running thread. After that, the thread that is running will be suspended for the specified time, which will allow other (if any) parallel-executing threads to execute.

In the Java documentation, the general form of the sleep() method is as follows

public static void sleep(long millis) throws InterruptedException

here

  • millis – the number of milliseconds for which the thread is suspended.

If you need to set a delay of 1 second, then the call to the sleep() method in the program code can be, for example, like this:

...

try {
  Thread.sleep(1000);

  // Thread execution code
  // ...
}
catch (InterruptedException e) {
  // ...
}

Example. The example creates a delay of 2 seconds for the main and child threads.

// Thread encapsulating class
class MyThread implements Runnable {

  public void run() {
    // Start of thread execution
    System.out.println("MyThread.run() - begin");

    // Set a delay of 2 seconds
    try {
      Thread.sleep(2000);
    }
    catch (InterruptedException e) {
      e.getMessage();
    }

    // End of thread execution
    System.out.println("MyThread.run() - end");
  }
}

public class Threads {

  public static void main(String[] args) throws InterruptedException {
    // Display a message that the main thread is running
    System.out.println("Main thread - begin");

    // Create the instance of MyThread class
    MyThread mt = new MyThread();

    // Create a child thread in the main thread,
    // pass it an instance of mt
    Thread thr = new Thread(mt, "Thread - mt");

    // Run the thread using the start() method
    thr.start();
    // thr.run(); - so you can too

    // Suspend execution of the main thread for 2 seconds
    Thread.sleep(2000);

    // Inform about the end of the main thread
    System.out.println("Main thread - end");
  }
}

 


Related topics