Categories
Uncategorized

Three ways [of those things] of concurrent threads created

Create a thread can be said to be complicated by the knowledge of the most basic operation, the way to create threads of the JDK, if not included by the thread pool, then there are three forms, which are through inheritance Thread class, by implementing Runable interface through FutureTask . As shown below

The following three methods compiled a specific use of the similarities and differences.

3 ways to create a thread

1. inherited Thread

    Create a class that inherits Thread and override the run method

class MyThread extends Thread {
    @Override
    public void run() {
        String threadName = getName();
        for (int i = 0; i < 20; i++) {
            System.out.println("线程[" + threadName + "]运行开始,i = " + i + " time = " + new Date());
        }
    }
}

    Create and start a thread

        MyThread myThread1 = new MyThread();
        MyThread myThread2 = new MyThread();

        myThread1.start();
        myThread2.start();

        String threadName = Thread.currentThread().getName();
        for (int i = 0; i < 20; i++) {
            System.out.println("线程[" + threadName + "]运行开始,i = " + i + " time = " + new Date());
        }

The overall process is as follows:

This step is relatively simple and clear

    Create a class to inherit this type Thread

    Thread run method of coverage, and achieve your multi-threaded task in this method

    Create an instance of this class

    Calling its start () method (to note here, the novice is easy to directly call the run method, just as ordinary calls, but not multi-threaded calls)

2. To achieve Runnable

    Runable create a class that implements the interface, and override the run method

class MyRunable implements Runnable {
    
    @Override
    public void run() {
        String threadName = Thread.currentThread().getName();
        for (int i = 0; i < 20; i++) {
            System.out.println("线程[" + threadName + "]运行开始,i = " + i + " time = " + new Date());
        }
    }
}

    Achieve the creation of the class, and pass it to the constructor to create Thread Thread

MyRunable myRunable = new MyRunable();

new Thread(myRunable).start();
new Thread(myRunable).start();

String threadName = Thread.currentThread().getName();
for (int i = 0; i < 20; i++) {
    System.out.println("线程[" + threadName + "]运行开始,i = " + i + " time = " + new Date());
}

The overall process is as follows:

Specific steps are as follows:

    Create a class that implements the interface Runable

    Covering the run method, and achieve your multi-threaded task in this method

    Runable interface creates an instance of the class

    By way of example Runable interface on the class obtained in step, parameters are passed Thread constructor to create instances of Thread

    start calling on steps come Thread instance () method (to note here, the novice is easy to directly call the run method, just as ordinary calls, but not multi-threaded calls)

3. By FutureTask

    Create a class that implements the Callable interface, and implements call method (T represents the return type you want)

class MyCallerTask implements Callable {
    
    @Override
    public String call() throws Exception {
        System.out.println("执行任务开始");
        Thread.sleep(3000);
        System.out.println("执行任务结束");
        return "hello";
    }
}

    Create and start a thread

        // 创建异步任务
        FutureTask futureTask = new FutureTask<>(new MyCallerTask());
        // 启动线程
        new Thread(futureTask).start();
        System.out.println("其它操作");
        try {
            // 等待任务执行完,并获得任务执行完的结果
            String result = futureTask.get();
            System.out.println(result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

The overall process is as follows:

Specific steps are as follows:

    Create a class that implements the Callable interface, where T is the type of job you want to return to the type of thread

    Covered call approach and achieve your multi-threaded task in this method

    Callable interface creates an instance of the class

    By way of example Callable interface on the class obtained in step, it is transmitted to FutureTask argument constructor to create an instance of FutureTask

    Examples of the last step by FutureTask obtained, parameters are passed Thread constructor to create instances of Thread

    start calling on steps come Thread instance () method (to note here, the novice is easy to directly call the run method, just as ordinary calls, but not multi-threaded calls)

    If you want to get a return value, need to call FutureTask instance get () method (pay attention here, get () blocks the thread)

The advantages and disadvantages of the three methods

Presentation by the above codes, you can see these three methods, in fact, have advantages and disadvantages

Complexity

通过代码量与逻辑可以明显感觉出来,第一种直接继承 Thread 最方便,并且其它两种到最后,还是要依赖创建 Thread 才能实现。所以从方便及难易程度来看,可以得到如下结论:

Scalability

通过演示代码可以看出,只有第一种是通过继承,其它两种是通过实现接口的形式。我们都知道 JAVA 是不允许多继承,但是可以多实现。所以如果使用了第一种方法,就无法再继承别的类了。另外第一种把线程与线程任务冗余在了一起,不利于后期的维护。所以可以得到如下结论:

Is there a return value

从代码中可以很容易看出,只有通过 FutureTask 的方式才有返回值,另外两种均没有,所以得出如下结论

The thread is created in what way

If you want to return a value, that do not want, certainly you can only use the method of FutureTask. If you did not ask for the return value, and that Thread Runable can, however, take into account scalability, the best use of the form Runable. However, having said that, if used in a real project, considering the general, or to create the most recommended by the thread pool.

Leave a Reply