Introduction to the Java Concurrency Library

1. Traditional thread creation method

       Integrate the Thread class, rewrite the run method; implement the Runnable interface, rewrite the run method, and pass the Runnable interface implementation to Thread.

2. Thread mutual exclusion technology----synchronized

    Synchronized can be used in methods and code blocks to prevent concurrency problems when multiple threads work on the same data source.

            public synchronized void Method1(){ ...... }

            synchronized (Object o){ ...... }

3.ThreadLocal handles shared data between threads

    This class provides thread-local variables. Each thread that accesses a variable (through its get or set methods) has its own local variable, which is independent of the initialized copy of the variable. Similar to the map collection, except that there is no need to specify the key value here, the key value here defaults to the current thread.

    ThreadLocal<T> threadLocal = new ThreadLocal<T>();

    threadLocal.set(new T());

    T t = threadLocal.get();

4. Thread pool Executors

    Executors are used to create thread pools, commonly used static methods:
        

newFixedThreadPool(int nThreads) Create a fixed number of thread pools
newCachedThreadPool() Create a cached thread pool
newSingleThreadExecutor () Create a single thread
   

The return value type is ExecutorService

ExecutorService service = Exrcutors.newFixedThreadPllo(5); Create five threads

service.execute(new Runnable(){...}); execute thread task

5. Callable interface

  The Callable interface is similar to Runnable, both are designed for classes whose instances may be executed by another thread. But Runnable doesn't return results and cannot throw checked exceptions. Callable can return a result, and this return value can be obtained by Future, that is, Future can obtain the return value of asynchronously executing tasks  .

    Implementing the Callable<T> interface requires overriding the call method.

ExecutorService service = Exrcutors.newSingleThreadExecutor(); Create a thread

Futrue<T> future = service.submit( new Callable<T>(){ public T call(){ ......} ); Execute thread task

If multiple threads execute Callable tasks and return multiple Futures, you need to use the CompletionService<T> interface

    ExecutorService service = Exrcutors.newFixedThreadPllo(5); Create five threads

    CompletionService<T> completionService = new ExecutorCompletionService<T>(service); put the thread pool in

completionService.summit(new Callable(){...}); Execute thread tasks

   Future<T> future = completionService.take(); Get and remove the Future representing the next completed task,

                                               If no such task currently exists, wait

    future.get();

About Future:

Future represents the result of an asynchronous computation. It provides methods to check whether the calculation is complete, to wait for the completion of the calculation, and get the result of the calculation.

After the calculation is completed, only the get method can be used to obtain the result, if necessary, this method can be blocked until the calculation is completed. Cancellation is performed by the cancel method.

Additional methods are provided to determine whether a task completed normally or was canceled. Once a calculation is complete, it cannot be cancelled.

6. Thread lock Lock

    The Lock function is similar to synchronized, and it is easy to use.

    Lock lock = new ReentrantLock();

    lock.lock();

    lock.unLock();

7. ReadWriteLock

Locks are divided into read locks and write locks. Read locks and read locks are not mutually exclusive, read locks and write locks are mutually exclusive, and write locks and write locks are mutually exclusive, which is controlled by JVM itself

ReadWriteLock rwk = new ReentrantReadWriteLock();

读锁:rwk.readLock().lock();

     rwk.readLock().unlock();

写锁:rwk.writeLock().lock();

     rwk.writeLock().unlock();

8.Condition conditional blocking

    Conditon can be used to replace the traditional wait() and notify() methods;

    Condition must be used with Lock, without Lock, Condition cannot be used.

        Lock lock = new ReentrantLock();

        Condition condition = lock.newCondition();

        lock.lock(); ...... condition.await(); ......condition.signal();//唤醒某一个线程

9.Semaphore线程同步工具

    Semaphore通常用于限制访问某些资源的线程数,但是并未实现线程同步问题。常用方法acquire、release,用户获取和释放线程资源。

        ExecutorService service = Executors.newCachedThreadPool();//使用并发库,创建缓存的线程池  

        Semaphore sp = new Semaphore(3);//创建一个Semaphore信号量,并设置最大并发数为3

               new Thread(new Runnable() {

                                    public void run(){ .... sp.acquire(); ...... sp.release()});

10.CyclicBarrier线程同步工具

        CyclicBarrier可以使不同的线程彼此等待,等这些不同的线程都执行完了,再执行下面的程序。一般用于主任务执行需要所有的子任务执行完毕的功能需求中。

        ExecutorService service = Executors.newCachedThreadPool();

    CyclicBarrier cb = new CyclicBarrier(2);//设置2个等待线程,2个线程都执行完,再执行后面的程序。

    new Runnable(){

        public void run(){ runnable1; cb.await(); runnable2; cb.await(); };

11.Exchanger线程同步工具

        Exchanger只能用于两个线程之间交换数据,如果是多个线程运行,一次也只能在两个线程间交换数据。

        只有当每个线程都在进入 exchange ()方法并给出对象时,才能接受其他线程返回时给出的对象。







Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324463497&siteId=291194637