Basics of threads and Callable in Java [Beginner]

Thread basics in Java

If you use multithreading, you can run multiple processes in parallel. Each of these processes is called a thread. There are two ways to perform thread processing in Java, one is to use inheritance (extends) and the other is to implement an interface (implements). In the former case, inherit the Thread class and call thestart ()method. In the latter case, implement the Runnable interface and call therun ()method. Since multiple inheritance is not possible in Java, other classes cannot be inherited by the method using Thread, but it is possible by the method using the interface. In the latter case, you can also implement the Callable interface and call thecall ()method.

Difference between Runnable and Callable

In the case of Runnable, the return value cannot be specified and exceptions cannot be skipped.


public interface Runnable {
    public abstract void run();

Implement it like this. Override the run () method.


static class MyRunnable implements Runnable {
    public void run() {
        System.out.println("It's Runnable");

In the case of Callable, the return value can be specified and an exception can be skipped.


public interface Callable<V> {
    V call() throws Exception;

Implement it like this. Override the call () method. The <> part is called generics, and you can specify the return type. (String below)


static class MyCallable implements Callable<String> {
    public String call() throws Exception {
        String result = "Callable";
        return result;


I want to create an object and use Callable.


MyCallable myCallable = new MyCallable();

It is convenient to use Future and ExecutorService here.


//Create an ExecutorService instance
ExecutorService executorService = Executors.newSingleThreadExecutor();
//Ask the Executor to execute the thread
Future<String> future = executorService.submit(myCallable); 
//Get to retrieve the result()Use method
String result = future.get(100, TimeUnit.MILLISECONDS);

Execute myCallable via ExecutorService and store the result in a variable of type Future. The return type is specified by generics. In the above, it is set to String. The result is retrieved using the get () method of Future. Also, by specifying the argument as above, you can raise an exception if it takes 0.1 seconds or more.

For me, who doesn't understand well ** "Can't you just ()directly like you did with Runnable?" ** I thought, Since the processing of myCallable is done in a separate thread, you have to wait for the return value to be returned after the processing is completed. I think that if you use ExucutorService, you can get the return value via the future object after waiting until the processing is completed properly. (Maybe) The name Future is also futuristic.

Method using ThreadLocal

Since the static member of class is managed as a shared resource, it can be rewritten by another thread. It is convenient to use ThreadLocal to complete within the threat.


//Create an instance of ThreadLocal
private final ThreadLocal<ExecutorService> executorServicePool = new ThreadLocal<>();
//Set SingleThreadExecutor
//Get to retrieve the result()Use method
ExecutorService executorService = executorServicePool.get();

This makes it more thread-safe.

Referenced page

Recommended Posts

Basics of threads and Callable in Java [Beginner]
Basics of java basics ② ~ if statement and switch statement ~
Discrimination of Enums in Java 7 and above
Callable Interface in Java
Various threads in java
I summarized the types and basics of Java exceptions
Use of Abstract Class and Interface properly in Java
Basics of character operation (java)
Summary of Java language basics
Implementation of gzip in java
Advantages and disadvantages of Java
Implementation of tri-tree in Java
[For beginners] Explanation of classes, instances, and statics in Java
Command to check the number and status of Java threads
Solve AtCoder Beginner Contest 151 in java
Basics of conditional branching and return
Differences between "beginner" Java and Kotlin
Solve AtCoder Beginner Contest 150 in java
Basics of sending Gmail in Ruby
Encoding and Decoding example in Java
Solve AtCoder Beginner Contest 153 in java
[Java beginner] About abstraction and interface
[Java beginner] == operator and equals method
StringBuffer and StringBuilder Class in Java
Solve AtCoder Beginner Contest 175 in java
Solve AtCoder Beginner Contest 160 in java
List of members added in Java 9
[Java] Judgment of identity and equivalence
Understanding equals and hashCode in Java
Solve AtCoder Beginner Contest 152 in java
Solve AtCoder Beginner Contest 156 in java
List of types added in Java 9
Implementation of like function in Java
Hello world in Java and Gradle
[Java] Get the dates of the past Monday and Sunday in order
[Java8] Proper use of Comparable and Comparator in terms of employee sorting
Basics of Java development ~ How to write programs (variables and types) ~
Mechanism and characteristics of Collection implementation class often used in Java
[Java] I participated in ABC-188 of Atcorder.
Implementation of DBlayer in Java (RDB, MySQL)
Get the result of POST in Java
Difference between final and Immutable in Java
java beginner 4
The story of forgetting to close a file in Java and failing
[# 1 Java] Basics of Java-Major premise before studying-
[Java] for Each and sorted in Lambda
java beginner 3
Java basics
[Java] Inheritance and structure of HttpServlet class
Summary of hashes and symbols in Ruby
java beginner
[Ruby basics] About the role of true and break in the while statement
Java basics
[day: 5] I summarized the basics of Java
This and that of the implementation of date judgment within the period in Java
[Java / Swift] Comparison of Java Interface and Swift Protocol
Looking back on the basics of Java
Comparison of thread implementation methods in Java and lambda expression description method
[Java beginner] About initialization of multidimensional array
[Ruby] Classification and usage of loops in Ruby
Arrylist and linked list difference in java