[Java] How to implement multithreading

Introduction

This time, I will explain how to implement Java multithreading. Multithreading is used when you want to perform multiple processes in parallel.

Also, multithreading uses a class called Thread, I would like to introduce a method that is often used in the Thread class.

After that, it will be explained in the following versions and environments.

IDE:eclipse Java version: 8 OS:Mac OS

Then, I will explain it immediately.

1. Folder structure

The folder structure of the sample source created this time is as follows.

スクリーンショット 2018-11-12 20.57.13.png

2. Implementation of multi-thread processing

2-1. Outline of sample program

As for the contents to be implemented in this sample, we will implement a basic program that starts the main class "Main.java" and starts the subclasses "SubThreadA.java" and "SubThreadB.java" in parallel. ..

2-2. Subclass implementation

First, implement the subclass that you want to process in parallel this time.

To create a multithreaded program, inherit the Thread class and write the run method in that class. Describe as follows.

class subclass name extends Thread{
    public void run() {
processing
    }
}

In this sample program, let's implement a program that outputs the following words to the console in each thread.

SubThreadA.java → "Thread A has started." SubThreadB.java → "Thread B has started."

SubThreadA.java


package main;

public class SubThreadA extends Thread {
    public void run() {
        System.out.println("Thread A has started.");
    }
}

SubThreadB.java


package main;

public class SubThreadB extends Thread {
    public void run() {
        System.out.println("Thread B has started.");
    }
}

2-3. Main class implementation

Next, implement the process to start the thread created earlier in the main class.

As for the implementation method, the process of the run method is started in multithread by calling the start method from the object of the subclass created earlier.

Describe as follows.

    public static void main(String[] args) {
Subclass name mt=new subclass name();
        mt.start();
}

Now, let's describe the process of calling "SubThreadA" and "SubThreadB".

main.java


package main;

public class Main {
    public static void main(String[] args) {
        //Creating a subclass object that inherits the Thread class
        SubThreadA mt1 = new SubThreadA();
        SubThreadB mt2 = new SubThreadB();

        //Subclass execution
        mt1.start();
        mt2.start();
    }
}

After completing the above description, right-click Main.java> Run Java Application to execute it. It is OK if the following words are output on the console screen.

Thread A has started.
Thread B has started.

3. Implementation of sleep method

Here, we will explain how to stop a thread for a certain period of time with the sleep method of the Thread class.

The sleep method is used by specifying the time you want to stop in the argument in milliseconds. (1000 milliseconds = 1 second)

Also, in the sleep method, an InterruptedException exception may occur due to an interrupt, etc., so it is necessary to enclose it in a try-catch statement and handle the exception.

Now, let's execute "Sub Thread A" with a delay of 3 seconds.

SubThreadA.java


package main;

public class SubThreadA extends Thread {
    public void run() {
        try {
        //3 seconds sleep
        Thread.sleep(3000);
        System.out.println("Thread A has started.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Right-click on Main.java> Run Java Application to run it. It is OK if thread A is started 3 seconds after thread B and the words are output to the console screen in the following order.

Thread B has started.
Thread A has started.

4. Implementation of join method

Use the join method when you want to wait until the processing of another thread finishes. Code the thread object .join () that you want to monitor for termination.

Also, as with the sleep method, an InterruptedException exception may occur due to an interrupt, etc., so it is necessary to enclose it in a try-catch statement and handle the exception.

Now, let's try to process "SubThreadB" after the processing of "SubThreadA" is completed.

Main.java


package main;

public class Main {
    public static void main(String[] args) {
        try {
            SubThreadA mt1 = new SubThreadA();
            SubThreadB mt2 = new SubThreadB();

            mt1.start();
            mt1.join();  //Wait until SubThreadA finishes
            mt2.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Right-click on Main.java> Run Java Application to run it. After a while, it is OK if threads A → B are executed in this order and the following words are output on the console screen.

Thread A has started.
Thread B has started.

at the end

I started my personal blog in 2020!

Based on the knowledge and experience gained as a freelance engineer, we plan to distribute content such as information about freelance engineers, IT technical information, industry information, and engineer life hacks.

The number of articles is still small, but it is updated weekly, so if you are interested, I would be grateful if you could take a look.

https://yacchi-engineer.com/

Recommended Posts

[Java] How to implement multithreading
How to implement date calculation in Java
How to implement Kalman filter in Java
How to implement coding conventions in Java
How to lower java version
[Java] How to use Map
Java --How to make JTable
How to use java Optional
How to minimize Java images
How to write java comments
How to use java class
[Java] How to display Wingdings
[Java] How to use string.format
How to use Java Map
How to set Java constants
How to use Java variables
How to convert Java radix
[Rails] How to implement scraping
[Java] How to use Optional ①
How to initialize Java array
Summary of how to implement default arguments in Java
Studying Java # 6 (How to write blocks)
[Java] How to update Java on Windows
How to make a Java container
How to disassemble Java class files
How to use Java HttpClient (Post)
[Java] How to use join method
How to learn JAVA in 7 days
[Processing × Java] How to use variables
[Java] How to create a folder
How to decompile java class files
[Java] How to use LinkedHashMap class
[JavaFX] [Java8] How to use GridPane
How to write Java variable declaration
[Java] Try to implement using generics
How to use class methods [Java]
[Rails] How to implement star rating
[Java] How to use List [ArrayList]
How to use classes in Java?
How to name variables in Java
How to pass Oracle Java Silver
Try to implement Yubaba in Java
How to turn Iterator Dojo (Java)
java Eclipse How to debug javaScript
[Processing × Java] How to use arrays
How to make a Java array
How to use Java lambda expressions
[Java] How to use Math class
How to find Java prime numbers
How to use Java enum type
How to concatenate strings in java
How to check Java installed on Mac
How to make a Java calendar Summary
How to implement search functionality in Rails
Multilingual Locale in Java How to use Locale
[Java] How to use the File class
How to compile Java with VsCode & Ant
[Java] How to use the hasNext function
[Java] How to compare with equals method
Try to implement n-ary addition in Java
[java] Summary of how to handle char