Java 基础
Java 容器
Java 并发
设计模式
目录

Thread Usage

# Thread Usage

There are three ways to use threads:

  • Implement the Runnable interface;

  • Implement the Callable interface;

  • Inherit the Thread class.

Classes that implement the Runnable and Callable interfaces can only be regarded as tasks that can be run in threads, not real threads, so they need to be called by Thread in the end. It can be understood that tasks are executed by thread drive.

# Implement the Runnable interface

You need to implement the run() method in the interface.

package com.code.concurrent.example1;

public class MyRunnable implements Runnable {
    @Override
    public void run() {
        // ...
    }
}
1
2
3
4
5
6
7
8

Use the Runnable instance to create another Thread instance, and then call the start() method of the Thread instance to start the thread.

package com.code.concurrent.example1;

public class Main {
    public static void main(String[] args) {
        MyRunnable instance = new MyRunnable();
        Thread thread = new Thread(instance);
        thread.start();
    }
}
1
2
3
4
5
6
7
8
9

# Implement Callable interface

Compared with Runnable, Callable can have a return value, which is encapsulated by FutureTask.

package com.code.concurrent.example2;

public class MyCallable implements Callable<Integer> {
    public Integer call() {
        return 123;
    }
}
1
2
3
4
5
6
7
package com.code.concurrent.example2;

public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyCallable mc = new MyCallable();
        FutureTask<Integer> ft = new FutureTask<>(mc);
        Thread thread = new Thread(ft);
        thread.start();
        System.out.println(ft.get());
    }
}
1
2
3
4
5
6
7
8
9
10
11

# Inheriting the Thread class

It is also necessary to implement the run() method, because the Thread class also implements the Runable interface.

When the start() method is called to start a thread, the virtual machine will put the thread into the ready queue to wait for scheduling. When a thread is scheduled, the run() method of the thread will be executed.

package com.code.concurrent.example3;

public class MyThread extends Thread {
    public void run() {
        // ...
    }
}
1
2
3
4
5
6
7
package com.code.concurrent.example3;

public class Main {
    public static void main(String[] args) {
        MyThread mt = new MyThread();
        mt.start();
    }
}
1
2
3
4
5
6
7
8

# Implementing an interface vs. inheriting Thread

Implementing an interface is better because:

  • Java does not support multiple inheritance, so if you inherit the Thread class, you cannot inherit other classes, but you can implement multiple interfaces;
  • A class may only require executable, and inheriting the entire Thread class is too expensive.
最近更新
01
In Code
02
In Code
03
In Code
更多文章>