编程知识 cdmana.com

Multi thread keyword sorting in Java

Java Medium Runable,Callable,Future,FutureTask,ExecutorService,Excetor,Excutors,ThreadPoolExcetor Here are the key words , And their usage .

First of all, we'll divide them into categories :

  • Runable,Callable
  • Future,FutureTask
  • ExecutorService,Executor,Excutors,ThreadPoolExcetor

About Ranable and Callable

First Java There are three ways to create threads in :

  • Inherit Thread class , Cover run Method
  • Realization Runable Interface , Realization run Method
  • Realization Callable Interface , Realization run Method

The advantages and disadvantages of the three implementations :

  • Inherit Thread, The reason of single inheritance , You can no longer inherit other classes , Get the current thread this
  • Realization Runable Interface , no return value , Get the current thread Thread.currentThread()
  • Realization Callable Interface , It can be done by Future.get() Get the return value , Get the current thread Thread.currentThread()

Inherit Thread, Two steps :

class DemoThread extends Thread {
    @Override
    public void run() {
        super.run();
        // Perform time-consuming operation...
    }
}// Join in Java Development and exchange :756584822 Blow water and chat together 
DemoThread t = new DemoThread();
t.start();

Inherit Thread class , Cover run() Method .
Create thread object and use start() Method to start the thread .
Realization Runable, It is generally used as follows :

new Thread(new Runnable() {
    @Override
    public void run() {
        // do something
    }
}).start();

For simplicity .
It's very troublesome to get the results of thread execution in the above two ways , You can't get it directly .JDK1.5 Added Callable, Callable Of call() Methods can return values and throw exceptions .Callable You can return the Future object .
Callable Source code :

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

Callable The basic use method :

FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() {
    @Override
    public Integer call() throws Exception {
        // do something
        return null;
    }
});
Thread thread = new Thread(futureTask);
thread.start();
Integer result = futureTask.get();

function Callable The mission can get a Future object , adopt Future Of get() Method to get the return value of thread execution . that ...Future,FutureTask What's the difference , How do you use it? ?
->next()

About Future and FutureTask

In order to get the execution result of thread , Introduced Future Of FutureTask, So what's their relationship , How to use ?
Future Class is located java.util.concurrent It's a bag , It's an interface :

public interface Future<V> {
    boolean cancel(boolean mayInterruptIfRunning);
    boolean isCancelled();
    boolean isDone();
    V get() throws InterruptedException, ExecutionException;
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}// Join in Java Development and exchange :756584822 Blow water and chat together 

Future Defined 5 A way :

  • boolean cancel(boolean
    mayInterruptIfRunning): Trying to cancel the execution of this task . If the task has been completed 、 Or cancelled , Or it can't be cancelled for some other reason , Then the attempt will fail . When calling
    cancel() when , If the call succeeds , And this task hasn't started yet , This task will never run . If the task has been started , be
    mayInterruptIfRunning Parameter determines whether the thread executing the task should be interrupted in a way that attempts to stop the task . After this method returns , Yes
    isDone() Subsequent calls of will always return true. If this method returns true, On the other hand isCancelled() Subsequent calls of will always return
    true.
  • boolean isCancelled(): If the task is cancelled before it is normally completed , Then return to true.
  • boolean isDone(): If the task has been completed , Then return to true.
    Probably due to normal termination 、 Complete with exception or cancellation , In all these cases , This method will all return true.
  • V get()throws
    InterruptedException,ExecutionException: If necessary, , Wait for completion of calculation , And then get the results .
  • V get(long timeout,TimeUnit unit) throws InterruptedException,
    ExecutionException, TimeoutException:
    If necessary, , Wait at most after the time given for the calculation to complete , Get the results ( If the results are available ).

in general Future Three functions are provided :

  • Determine if the task is completed ; Be able to interrupt tasks ;
  • Be able to get task execution results .

a key :
RunnableFuture Inherited Runnable Interface and Future Interface , and FutureTask Realized RunnableFuture Interface .
FutureTask The implementation of the :

public class FutureTask<V> implements RunnableFuture<V>

RunnableFuture Interface implementation :

public interface RunnableFuture<V> extends Runnable, Future<V> {
    void run();
}

FutureTask yes Future A unique implementation class of the interface .
Except that it can be used Thread packing FutureTask Outside , There's another way to use it :

ExecutorService executor = Executors.newCachedThreadPool();
FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() {
    @Override
    public Integer call() throws Exception {
        // do something
        return null;
    }// Join in Java Development and exchange :756584822 Blow water and chat together 
});
executor.submit(futureTask);
Integer result = futureTask.get();

It's used here Executor frame .
->next();

About ExecutorService,Executor,Excutors,ThreadPoolExcetor

Executor In the framework of Java 5 Introduced in ,Executor The framework is a call based on a set of execution policies 、 Dispatch 、 Framework of asynchronous tasks executed and controlled .
Say Executor Before the framework, we need to introduce a new concept —— Thread pool (ThreadPoolExecutor):

public ThreadPoolExecutor(intcorePoolSize,
        int maximumPoolSize,
        long keepAliveTime,
        TimeUnit unit,
        BlockingQueue<Runnable> workQueue,
        ThreadFactory threadFactory,
        RejectedExecutionHandler handler)
// Join in Java Development and exchange :756584822 Blow water and chat together 

ThreadPoolExecutor yes Executors The underlying implementation of class .
stay JDK In the help document , There is a passage like this :

“ It is strongly recommended that programmers use more convenient Executors Factory method Executors.newCachedThreadPool()( Unbounded thread pool , Automatic thread recycling can be done )、Executors.newFixedThreadPool(int)( Fixed size thread pool ) and Executors.newSingleThreadExecutor()( Single background thread ), They all have predefined settings for most usage scenarios .”

that ExecutorService,Excetor,Excutors What are they ?
Excetor Is an abstract level of the core interface :

public interface Executor {
    void execute(Runnable command);
}

ExecutorService Interface Yes Executor The interface has been extended , Provides a return Future object , End , Close the thread pool .

public interface ExecutorService extends Executor {
    void shutdown();
    // Join in Java Development and exchange :756584822 Blow water and chat together 
    <T> Future<T> submit(Callable<T> task);
    <T> Future<T> submit(Runnable task, T result);
    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException;
}

Executors Is a utility class , Be similar to Collections. Provide factory methods to create different types of thread pools , such as FixedThreadPool or CachedThreadPool.

public class Executors {
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
        }
        
     public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
        }
}

The above is right Java Multi thread keyword collation , Not a mess .

版权声明
本文为[Front end attack calf]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224152603259f.html

Scroll to Top