java several ways to create threads and contrast

1, inheritance Thread class to create a thread class

(1) define a subclass of the Thread class and override the run method of the class, method body that represents the run method of the thread to complete the task. Thus the run () method is called executable.

(2) create an instance of a subclass of Thread, the thread object is created.

(3) the calling thread object's start () method to start the thread.

 Code

package com.zoo.lion.modules.test.thread;

/**
 * @Author: xf
 * @Date: 2019/7/9 16:16
 * @Version 1.0
 */
public class ExtendsThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(getName() + " " + i);
        }
    }
}

test

    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName());
        new ExtendsThread().start();
    }

The above code Thread.currentThread () method returns the currently executing thread object. GetName () method returns the name of the thread that calls the method.

2, create threads through the Runnable interface class

(1) Definition runnable interface implementation class, interface and override the run () method, the method body run () method of the same thread of execution threads.

(2) create an instance of Runnable implementation class and use it as an example of a target to create Thread Thread object, the Thread object is the real thread object.

(3) the calling thread object's start () method to start the thread.

Code

package com.zoo.lion.modules.test.thread;

/**
 * @Author: xf
 * @Date: 2019/7/9 16:19
 * @Version 1.0
 */
public class ImplRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
        }
    }
}

test

    public static void main(String[] args) {
        ImplRunnable implRunnable = new ImplRunnable();
        new Thread(implRunnable, "线程1").start();
        new Thread(implRunnable, "线程2").start();
    }

Thread execution process is very simple, when executing code Start (), the object executes rewriting void run (); method, the method is performed after the completion, the thread disappeared.

3, create a thread through Callable and Future

First, look at the source code Callable Interface

package java.util.concurrent;

@FunctionalInterface
public interface Callable<V> {

    V call() throws Exception;

}

(1) Create Callable interface implementation class, and implements call () method, the call () method as a thread of execution, and return values.

(2) create an instance of the implementation class Callable using FutureTask packaging Callable object class, the object encapsulates FutureTask Callable object of the call () Returns the value of the method. (FutureTask is a wrapper that is created by accepting Callable, it also realized the Future and Runnable interface.)

(3) use FutureTask object creation and start a new thread as the target Thread object.

(4) calls FutureTask object's get () method to obtain the return value after the end of the sub-thread execution

Code

package com.zoo.lion.modules.test.thread;

import java.util.concurrent.Callable;

/**
 * @Author: xf
 * @Date: 2019/7/9 16:23
 * @Version 1.0
 */
public class ImplCallable implements Callable<String> {
    private int ticket = 10;
    @Override
    public String call() {
        while (this.ticket > 0) {
            System.out.println(Thread.currentThread().getName() + ":剩余票数:" + ticket--);
        }
        return "票卖完了";
    }
}

test

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ImplCallable implCallable = new ImplCallable();
        FutureTask<String> futureTask = new FutureTask<>(implCallable);
        new Thread(futureTask, "线程1").start();
        System.out.println("子线程的返回值:" + futureTask.get());
    }

Use create a thread pool to start

    public static void main(String[] args) {
        ImplCallable implCallable = new ImplCallable();
        // 创建一个线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        System.out.println("开始执行call()方法!");
        Future<String> future = executorService.submit(implCallable);
        try {
            System.out.println("这里是为了测试一下程序的执行。");
            System.out.println("调用call()方法返回的结果:" + future.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

Comparison of three methods Second, create a thread

1, using achieve Runnable, Callable way to create multi-threaded interface, the

Advantages are:

Thread class implements Runnable interface or just Callable interface, you can also inherit from other classes.

In this way, multiple threads may share the same target object, is the same for a plurality of threads to deal with a case where the same resources, which can be separated to form a clear model of the CPU, code and data, to better reflect the object-oriented thinking.

Disadvantages are:

Programming is slightly more complicated, if you want to access the current thread, you must use Thread.currentThread () method.

2, using inheritance Thread class when creating multi-threaded manner,

Advantages are:

Write simple, if you need access to the current thread, you do not need to use Thread.currentThread () method, the direct use this to get the current thread.

Disadvantages are:

Thread class Thread class has been inherited, so can not inherit other parent.

3 difference, Runnable and Callable of

(1) Callable predetermined (override) is a method call (), Runnable predetermined (override) method is run ().

(2) Callable task execution returns a value, and the task is not Runnable return value.

(3) call method can throw an exception, run method can not.

(4) Run the task can get a Future Callable object that represents the result of an asynchronous computation. It provides a method of checking computation is complete, to wait for the completion of calculation, and calculation of the search result. By Future object can understand the implementation of the mandate, to cancel the execution of the task, but also get the results.

Guess you like

Origin blog.csdn.net/qq_36850813/article/details/95311194