[Hard Java Concurrency] JAVA Multithreaded: Thread Creation Using JDK5.0 New Thread Creation Method

Keywords: Java Big Data

This article is about Learning Guide for Big Data Specialists from Zero (Full Upgrade) Java concurrency supplement for.

1 New way 1: Implement Callable interface

Callable is more powerful than Runnable

  • Can have a return value compared to the run() method
  • Method can throw an exception
  • Return values supporting generics
  • You need to use the FutureTask class, for example, to get the returned results

Future interface

  • You can cancel the execution results of specific Runnable, Callable tasks, query whether completed, get results, and so on.
  • FutrueTask is the only implementation class for the Futrue interface
  • FutureTask also implements Runnable, Future interface. It can be used as both
  • Runnable is executed by a thread and can be used as Future to get the return value of Callable
package com.atguigu.java2;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Three ways to create threads: implement the Callable interface. --- JDK 5.0 added
 *
 *
 * How do you understand that creating multithreads is a more powerful way to implement the Callable interface than implementing the Runnable interface?
 * 1. call()Can have a return value.
 * 2. call()You can throw exceptions, be caught by outside operations, and get information about exceptions
 * 3. Callable Is generic supported
 *
 * @author shkstart
 * @create 2019-02-15 6:01 p.m.
 */
//1. Create an implementation class that implements Callable
class NumThread implements Callable{
    //2. Implement the call method, declaring the operations this thread needs to perform in call()
    @Override
    public Object call() throws Exception {
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            if(i % 2 == 0){
                System.out.println(i);
                sum += i;
            }
        }
        return sum;
    }
}


public class ThreadNew {
    public static void main(String[] args) {
        //3. Create object of Callable interface implementation class
        NumThread numThread = new NumThread();
        //4. Create FutureTask objects by passing objects of this Callable interface implementation class to the FutureTask constructor
        FutureTask futureTask = new FutureTask(numThread);
        //5. Pass the object of FutureTask as an argument to the constructor of the Thread class, create the Thread object, and call start()
        new Thread(futureTask).start();

        try {
            //6. Get the return value of the call method in Callable
            //The return value of get() is the return value of call() whose FutureTask constructor parameter Callable implements a class override.
            Object sum = futureTask.get();
            System.out.println("The sum is:" + sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

}

2 New Method 2: Use Thread Pool

Background: Often created and destroyed resources that are particularly heavily utilized, such as threads in concurrent situations, can have a significant impact on performance.

Idea: Create many threads in advance, put them in the thread pool, get them directly when using, and put them back into the pool when using them. You can avoid creating destruction and reuse frequently. Similar to public transportation in life.

Benefits:

Increase response speed (reduces time to create new threads)

Reduce resource consumption (reuse threads in the thread pool, do not need to be created every time)

Easy Thread Management

corePoolSize: Core pool size

maximumPoolSize: Maximum number of threads

keepAliveTime: The maximum amount of time a thread can be held without a task before it terminates

Thread pool related API s

Thread pool related API s: ExecutorService and Executors have been available since JDK 5.0

ExecutorService: True thread pool interface. Common subclass ThreadPoolExecutor

void execute(Runnable command): executes a task/command with no return value and is generally used to execute Runnable

<T> Future<T> submit (Callable<T> task): Execute a task, have a return value, and generally execute Callable

void shutdown(): close connection pool

Executors: Tool class, factory class for thread pools, used to create and return different types of thread pools

Executors.newCachedThreadPool(): Create a thread pool that creates new threads as needed

Executors.newFixedThreadPool(n);Create a thread pool that can reuse a fixed number of threads

Executors.newSingleThreadExecutor(): Create a thread pool with only one thread

Executors.newScheduledThreadPool(n): Creates a thread pool that can be scheduled to run commands after a given delay or to execute them periodically.

package com.atguigu.java2;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Four ways to create threads: using thread pools
 *
 * Benefits:
 * 1.Increase response speed (reduces time to create new threads)
 * 2.Reduce resource consumption (reuse threads in the thread pool, do not need to be created every time)
 * 3.Easy Thread Management
 *      corePoolSize: Core pool size
 *      maximumPoolSize: Maximum Threads
 *      keepAliveTime: The maximum amount of time a thread can remain without a task before it terminates
 *
 *
 * Interview question: How many ways to create multithreads? Four!
 * @author shkstart
 * @create 2019-02-15 6:30 p.m.
 */

class NumberThread implements Runnable{

    @Override
    public void run() {
        for(int i = 0;i <= 100;i++){
            if(i % 2 == 0){
                System.out.println(Thread.currentThread().getName() + ": " + i);
            }
        }
    }
}

class NumberThread1 implements Runnable{

    @Override
    public void run() {
        for(int i = 0;i <= 100;i++){
            if(i % 2 != 0){
                System.out.println(Thread.currentThread().getName() + ": " + i);
            }
        }
    }
}

public class ThreadPool {

    public static void main(String[] args) {
        //1.Provides a thread pool for a specified number of threads
        ExecutorService service = Executors.newFixedThreadPool(10);
        ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;
        //Set Thread Pool Properties
//        System.out.println(service.getClass());
//        service1.setCorePoolSize(15);
//        service1.setKeepAliveTime();


        //2. Perform the operation of the specified thread. Objects that implement the Runnable interface or Callable interface implementation class need to be provided
        service.execute(new NumberThread());//Suitable for Runnable
        service.execute(new NumberThread1());//Suitable for Runnable

//        service.submit(Callable callable);//Suitable for Callable
        //3. Close connection pool
        service.shutdown();
    }

}

Posted by Brunda on Thu, 23 Sep 2021 11:45:39 -0700