Java 并发包

作者: 93张先生 | 来源:发表于2019-11-21 22:38 被阅读0次
主要包含:

原子类 AutomaticLong
Lock Synchroize voliate
线程集合 concurrentHashMap
线程执行框架 Thread Runable Callable Future ThreadPool executor
线程工具 countDownLatch semaphore

1.Executor 是一个接口,它解耦了Task任务提交和执行;

* An object that executes submitted {@link Runnable} tasks. This
 * interface provides a way of decoupling task submission from the
 * mechanics of how each task will be run, including details of thread
 * use, scheduling, etc.  An {@code Executor} is normally used
 * instead of explicitly creating threads. For example, rather than
 * invoking {@code new Thread(new(RunnableTask())).start()} for each
 * of a set of tasks, you might use:
 *
 * <pre>
 * Executor executor = <em>anExecutor</em>;
 * executor.execute(new RunnableTask1());
 * executor.execute(new RunnableTask2());
 * The {@code Executor} implementations provided in this package
 * implement {@link ExecutorService}, which is a more extensive
 * interface.  The {@link ThreadPoolExecutor} class provides an
 * extensible thread pool implementation. The {@link Executors} class
 * provides convenient factory methods for these Executors.
public interface Executor {

    /**
     * Executes the given command at some time in the future.  The command
     * may execute in a new thread, in a pooled thread, or in the calling
     * thread, at the discretion of the {@code Executor} implementation.
     *
     * @param command the runnable task
     * @throws RejectedExecutionException if this task cannot be
     * accepted for execution
     * @throws NullPointerException if command is null
     */
    void execute(Runnable command);
}

ExecutorService 是一个比Executor更具有扩展性的接口,提供了管理线程终止的方法,和跟踪一个或多个异步任务的结果Future的方法;

* An {@link Executor} that provides methods to manage termination and
* methods that can produce a {@link Future} for tracking progress of
* one or more asynchronous tasks.
*
* <p>An {@code ExecutorService} can be shut down, which will cause
* it to reject new tasks.  Two different methods are provided for
* shutting down an {@code ExecutorService}. The {@link #shutdown}
* method will allow previously submitted tasks to execute before
* terminating, while the {@link #shutdownNow} method prevents waiting
* tasks from starting and attempts to stop currently executing tasks.
* Upon termination, an executor has no tasks actively executing, no
* tasks awaiting execution, and no new tasks can be submitted.  An
* unused {@code ExecutorService} should be shut down to allow
* reclamation of its resources.
*
* <p>Method {@code submit} extends base method {@link
* Executor#execute(Runnable)} by creating and returning a {@link Future}
* that can be used to cancel execution and/or wait for completion.
* Methods {@code invokeAny} and {@code invokeAll} perform the most
* commonly useful forms of bulk execution, executing a collection of
* tasks and then waiting for at least one, or all, to
* complete. (Class {@link ExecutorCompletionService} can be used to
* write customized variants of these methods.)
*
* <p>The {@link Executors} class provides factory methods for the
* executor services provided in this package.
*
public interface ExecutorService extends Executor 

AbstractExecutorService提供了ExecutorService的基本实现

* Provides default implementations of {@link ExecutorService}
* execution methods. This class implements the {@code submit},
* {@code invokeAny} and {@code invokeAll} methods using a
* {@link RunnableFuture} returned by {@code newTaskFor}, which defaults
* to the {@link FutureTask} class provided in this package.  For example,
* the implementation of {@code submit(Runnable)} creates an
* associated {@code RunnableFuture} that is executed and
* returned. Subclasses may override the {@code newTaskFor} methods
* to return {@code RunnableFuture} implementations other than
* {@code FutureTask}.

public abstract class AbstractExecutorService implements ExecutorService 

ThreadPoolExecutor 提供了一个线程池的扩展的ExecutorService;

* An {@link ExecutorService} that executes each submitted task using
* one of possibly several pooled threads, normally configured
* using {@link Executors} factory methods.

public class ThreadPoolExecutor extends AbstractExecutorService

Executors 提供了方便的创建Executor 的工厂方法;其中多种线程池创建方法,都是创建的ThreadPoolExecutor的实例;

* Factory and utility methods for {@link Executor}, {@link
* ExecutorService}, {@link ScheduledExecutorService}, {@link
* ThreadFactory}, and {@link Callable} classes defined in this
* package. This class supports the following kinds of methods:
    
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>());
}

RunnableFuture

/**
 * A {@link Future} that is {@link Runnable}. Successful execution of
 * the {@code run} method causes completion of the {@code Future}
 * and allows access to its results.
 * @see FutureTask
 * @see Executor
 * @since 1.6
 * @author Doug Lea
 * @param <V> The result type returned by this Future's {@code get} method
 */
public interface RunnableFuture<V> extends Runnable, Future<V> {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();
}

Future 是一个异步计算结果的代表;可取消cancle(),可同步等待完成get();


/**
 * A {@code Future} represents the result of an asynchronous
 * computation.  Methods are provided to check if the computation is
 * complete, to wait for its completion, and to retrieve the result of
 * the computation.  The result can only be retrieved using method
 * {@code get} when the computation has completed, blocking if
 * necessary until it is ready.  Cancellation is performed by the
 * {@code cancel} method.  Additional methods are provided to
 * determine if the task completed normally or was cancelled. Once a
 * computation has completed, the computation cannot be cancelled.
 * If you would like to use a {@code Future} for the sake
 * of cancellability but not provide a usable result, you can
 * declare types of the form {@code Future<?>} and
 * return {@code null} as a result of the underlying task.

public interface Future<V> 

future 例子

public class FutureExample {
   public static void main(String[] args) {
       ExecutorService executor = Executors.newFixedThreadPool(2);

       Future<String> future
               = executor.submit(new Callable<String>() {
           public String call() {
               try {
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               return "test-future";
           }
       });
       try {
           String result = future.get();
           System.out.println(result);
           executor.shutdown();
       } catch (InterruptedException e) {
           e.printStackTrace();
       } catch (ExecutionException e) {
           e.printStackTrace();
       }
   }
}

FutureTask是一个可以被取消的异步计算;它实现了Future和Runable接口;

* A cancellable asynchronous computation.  This class provides a base
* implementation of {@link Future}, with methods to start and cancel
* a computation, query to see if the computation is complete, and
* retrieve the result of the computation.  The result can only be
* retrieved when the computation has completed; the {@code get}
* methods will block if the computation has not yet completed.  Once
* the computation has completed, the computation cannot be restarted
* or cancelled (unless the computation is invoked using
* {@link #runAndReset}).

The {@link FutureTask} class is an implementation of {@code Future} that
* implements {@code Runnable}, and so may be executed by an {@code Executor}.

public class FutureTask<V> implements RunnableFuture<V>

RunnableFuture 是一个继承了 Runable接口的Future

* A {@link Future} that is {@link Runnable}. Successful execution of
* the {@code run} method causes completion of the {@code Future}
* and allows access to its results.

public interface RunnableFuture<V> extends Runnable, Future<V>

FutureTask的例子

public static void main(String[] args) {
    MyCallable callable1 = new MyCallable(5000);
    MyCallable callable2 = new MyCallable(6000);

    FutureTask<String> futureTask1 = new FutureTask<String>(callable1);
    FutureTask<String> futureTask2 = new FutureTask<String>(callable2);

    ExecutorService executor = Executors.newFixedThreadPool(2);
    executor.execute(futureTask1);
    executor.execute(futureTask2);

    while (true) {
        try {
            if(futureTask1.isDone() && futureTask2.isDone()){
                System.out.println("Done");
                //shut down executor service
                executor.shutdown();
                return;
            }

            if(!futureTask1.isDone()){
                //wait indefinitely for future task to complete
                //这里有一个get所以一直等待 futureTask1 完成,才执行下面的方法
                System.out.println("FutureTask1 output="+futureTask1.get());
            }

            System.out.println("Waiting for FutureTask2 to complete");
            String s = futureTask2.get(200L, TimeUnit.MILLISECONDS);
            if(s !=null){
                System.out.println("FutureTask2 output="+s);
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }catch(TimeoutException e){
            //do nothing
        }
    }

}

public class MyCallable implements Callable<String> {

    private long waitTime;

    public MyCallable(int timeInMillis){
        this.waitTime=timeInMillis;
    }
    @Override
    public String call() throws Exception {
        Thread.sleep(waitTime);
        //return the thread name executing this callable task
        return Thread.currentThread().getName();
    }

}

BlockingQueue是一个阻塞队列,支持元素不为空的时候取出来,队列中有空闲空间的时候放进去;

 A {@link java.util.Queue} that additionally supports operations
* that wait for the queue to become non-empty when retrieving an
* element, and wait for space to become available in the queue when
* storing an element.
方法:
method.png

http://www.importnew.com/28053.html

* An optionally-bounded {@linkplain BlockingQueue blocking queue} based on
* linked nodes.
* This queue orders elements FIFO (first-in-first-out).
* The <em>head</em> of the queue is that element that has been on the
* queue the longest time.
* The <em>tail</em> of the queue is that element that has been on the
* queue the shortest time. New elements
* are inserted at the tail of the queue, and the queue retrieval
* operations obtain elements at the head of the queue.
* Linked queues typically have higher throughput than array-based queues but
* less predictable performance in most concurrent applications.

public class LinkedBlockingQueue<E> extends AbstractQueue<E>
        implements BlockingQueue<E>, java.io.Serializable

未完待续......

相关文章

网友评论

    本文标题:Java 并发包

    本文链接:https://www.haomeiwen.com/subject/dapxwctx.html