Comparison of thread implementation methods in Java and lambda expression description method

Introduction

In a hurry, from the workplace to make a multithreaded program in Java I will summarize what I learned in haste to answer unreasonable requests.

Conclusion: If you want to start up quickly for the time being

If the path to subthread startup is small & you do not want to keep the subthread as an instance, combine lambda expressions

ThreadStartTemplate.java


new Thread( () -> {Method or process you want to execute in a subthread} ).start()

Looks good. It's convenient.

Execution environment

I put off installing Eclipse on my own and used paiza.io to check the grammar for the time being.

How to implement subthreads

It seems that threads can be implemented with the following two patterns.

  1. Use the Rnnable interface.
  2. Inherit the Thread class.

1. Use the Runnable interface

It seems that Java has a Runnable interface, and by overriding run (), it seems that the processing executed at the time of thread can be implemented. The usage is as follows.

  1. Create an instance of a class that implements the Runnable interface
  2. Pass a Runnnable object to the constructor to create a Thread type object
  3. Call the start () method of the Thread class to start a subthread

The sample code written according to this street is RunnableSample.java.

RunnableSample.java


import java.util.*;

public class Main {
    
    private static class RunnableSample implements Runnable{
        
        private String thread_no;
        RunnableSample(String str){
            this.thread_no = str;
        }
        public void run(){
            System.out.println("RunnableThread Starting No."+thread_no);
        }
    }
    
    public static void main(String[] args) throws Exception {
        String str1 = "1";
        String str2 = "2";
        RunnableSample runner1 = new RunnableSample(str1); // 1.
        RunnableSample runner2 = new RunnableSample(str2); // 1.
        Thread thread1 = new Thread(runner1); // 2.
        Thread thread2 = new Thread(runner2); // 2.
        thread1.start(); // 3.
        thread2.start(); // 3.
        
        Thread.sleep(200);
        System.out.println("MainThread End");
    }
}

Execution result


RunnableThread Starting No.1
RunnableThread Starting No.2
MainThread End

The RunnableSample class is defined as a local class of the Main class. Create an object of RunnableSample class from the main thread and execute it as two sub threads.

RunnableThread Starting No.1 RunnableThread Starting No.2 May be output in reverse order. The Main Thread End will usually be output last because it has a 200ms sleep in between.

2. Inherit the Thread class.

Next, I will write about how to implement the processing of subthreads by inheriting the Thread class. The usage is as follows. The code is ThreadSample.java.

  1. Create an instance of the class that overrides run () of the Thread class
  2. Call the start () method of the Thread class to start a subthread

ThreadSample.java


import java.util.*;

public class Main {
    
    private static class ThreadSample extends Thread{
        
        private String thread_no;
        ThreadSample(String str){
            this.thread_no = str;
        }
        public void run(){
            System.out.println("RunnableThread Starting No."+thread_no);
        }
    }
    
    public static void main(String[] args) throws Exception {

        String str1 = "1";
        String str2 = "2";
        ThreadSample thread1 = new ThreadSample(str1); // 1.
        ThreadSample thread2 = new ThreadSample(str2); // 1.
        thread1.start(); // 2.
        thread2.start(); // 2.
        
        Thread.sleep(200);
        System.out.println("MainThread End");
    }
}

Execution result


RunnableThread Starting No.2
RunnableThread Starting No.1
MainThread End

The execution result will be the same (this time, the output order of Thread1 and Thread2 was reversed).

After all, which is better, "implementation of Runnable interface" or "inheritance of Thread class"?

Basically, it seems that there are many advantages to using the Runnable interface.

--Java does not allow multiple inheritance, so if you inherit the Thread class, other classes will not be able to inherit it. Any class that implements the Runnable interface can inherit from other classes. --You don't have to inherit the overhead of the Thread class. --The code seems to be cleaner if you inherit the Thread class.

It would be perfect if I could write it neatly even with the Runnable interface. I will try it.

Simplify the description of the Runnable interface with a lambda expression.

Try to simplify the code with lambda expressions by referring to Understanding Java 8 lambda expressions.

LambdaThreadSample.java


import java.util.*;

public class Main {
    
    static private void subthread_run(String thread_no){
        System.out.println("RunnableThread Starting No."+thread_no);
    }
    
    public static void main(String[] args) throws Exception {

        String str1 = "1";
        String str2 = "2";
        new Thread( () -> {subthread_run(str1);} ).start();
        new Thread( () -> {subthread_run(str2);} ).start();
        
        Thread.sleep(200);
        System.out.println("MainThread End");
    }
}

Execution result


RunnableThread Starting No.2
RunnableThread Starting No.1
MainThread End

For the detailed description method, refer to Understanding Java 8 Lambda Expressions, but ~~ difficult to explain ~~ The RunnableSample class is an anonymous class with a subthread_run method, and the Thread class object is new and started. By using the lambda expression, the program became much cleaner and the readability was greatly improved. This is a good way to write if you don't need to manage Thread as an instance. Next, I would like to summarize Synchronized.

References

150 questions to train programming skills to fight in the world Chapter.16: Threads and locks

Recommended Posts

Comparison of thread implementation methods in Java and lambda expression description method
Java methods and method overloads
Implementation of gzip in java
Implementation of tri-tree in Java
Implement Thread in Java and try using anonymous class, lambda
[Java] Comparison method of character strings and comparison method using regular expressions
BloomFilter description and implementation sample (JAVA)
Implementation of like function in Java
Mechanism and characteristics of Collection implementation class often used in Java
Implementation of clone method for Java Record
Implementation of DBlayer in Java (RDB, MySQL)
[Java] for Each and sorted in Lambda
[Java / Swift] Comparison of Java Interface and Swift Protocol
[Java] Collection and StringBuilder operation method comparison
Discrimination of Enums in Java 7 and above
This and that of the implementation of date judgment within the period in Java
[Java] Handling of JavaBeans in the method chain
[Java] Personal summary of classes and methods (basic)
Check static and public behavior in Java methods
Basics of threads and Callable in Java [Beginner]
[Java] Is it unnecessary to check "identity" in the implementation of the equals () method?
Java8 to start now ~ forEach and lambda expression ~
[Java] Lambda expression
Java and Swift comparison (3) Class implementation / Class inheritance / Class design
Method name of method chain in Java Builder + α
Java lambda expression
[Java] Implementation method memo to set WS-Security Username Token in SOAP Stub of axis2
The comparison of enums is ==, and equals is good [Java]
Use of Abstract Class and Interface properly in Java
Equivalence comparison of Java wrapper classes and primitive types
Java8 Lambda expression & Stream design pattern reconsideration --Template Method pattern -
Interpreter implementation in Java
[Java] Thread and Runnable
java neutral lambda expression 1
[Java] String comparison and && and ||
Boyer-Moore implementation in Java
Java 8 lambda expression Feature
java lambda expression memo
Java lambda expression [memo]
Studying Java 8 (lambda expression)
Review java8 ~ Lambda expression ~
Java lambda expression again
Setting method to link Java of Eclipse and Github / September 2017
[For beginners] Explanation of classes, instances, and statics in Java
Same judgment / equal value judgment / comparison / order in Swift and Java
Define abstract methods in Java enum and write each behavior
Think about the differences between functions and methods (in Java)
Java8 Lambda Expression & Stream Design Pattern Rethinking --Chain of Responsibility Pattern -
[Java] New Thread generation method (2)
[Java] Functional interface / lambda expression
[Java] Generics classes and generics methods
[Java] Implementation of Faistel Network
Java8 stream, lambda expression summary
[Java] Timer processing implementation method
Advantages and disadvantages of Java
Benefits of Java static method
Java abstract methods and classes
Implementation of HashMap in kotlin
[Java] New Thread generation method (1)
Comparison of WEB application development with Rails and Java Servlet + JSP
Let's create a TODO application in Java 4 Implementation of posting function