Specific multi-threaded

  Multi-threaded code development using the actual frequency is very high, fluent in multi-threaded to improve the efficiency and level of the code of great help. Therefore, this paper demonstrates the theoretical knowledge and practical code for some of the problems common multi-thread.

  There are two ways to create a thread, one is the Thread class inheritance, the other one is to achieve Runnable interface. Difference between the two is: the nature of the Thread class inheritance is multiple threads to complete their respective tasks and achieve Runnable interface is the essence of multiple threads together to complete a task. Both methods have in common is the need to create multiple threads, the concept of reference "database connection pool" to create a database connection takes a lot of time. Similarly, a thread is created and destroyed a thread is relatively time-consuming operation, therefore, the concept of "thread pool" came into being. Let's demonstrate through the code, the code first, direct way to create multiple threads, the second is the code to create multiple threads by thread pool, the same accumulation of thousands of times, compared to time-consuming.

import java.util.concurrent.atomic.AtomicInteger;

public class Demo1 {
    private static volatile AtomicInteger atomicInteger = new AtomicInteger(0);

    public static void main(String[] args) {
        long l = System.currentTimeMillis();
        for (int i=0; i<1000; i++){
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    atomicInteger.incrementAndGet ();
                } 
            }); 
            Thread.start (); 
            the try { 
                Thread.join (); // must let the thread is blocked waiting for, or the equivalent of this thread has not been completed to switch to another thread, time is not exactly 
            } the catch (InterruptedException E) { 
                e.printStackTrace (); 
            } 
        } 
        System.out.println (System.currentTimeMillis () - L); 
        System.out.println (AtomicInteger); 
    } 
}

The code is a time-consuming operation is 453ms.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Demo2 {

    private static volatile AtomicInteger atomicInteger = new AtomicInteger(0);
    private static ExecutorService executorService = Executors.newFixedThreadPool(10);

    public static void main(String[] args) {
        long l = System.currentTimeMillis();
        for (int i=0; i<1000; i++){
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    atomicInteger.incrementAndGet();
                }
            });
        }
        executorService.shutdown();
        try {
            executorService.awaitTermination(1,TimeUnit.HOURS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(System.currentTimeMillis()-l);
        System.out.println(atomicInteger);
    }
}

Two time-consuming running code is 22ms. By consuming comparison, we can find, use the thread pool can significantly reduce the run time, because not every thread to create threads and destruction, the cognitive theory before verification.

 

About ExecutorService

  ExecutorService life cycle has run, closed to terminate the three states, which is running after it is created, call shutDown method to smooth closed, call shutDownNow method to force a close, the difference between the two methods is no longer acceptable after shutDown new tasks, but will the current task to finish before it closed; after shutDownNow regardless of the method has not been queued tasks waiting to be executed, will be forced to terminate. In the actual project development, we often use the method to terminate shutDown. Further, in order to prevent long waiting time, usually after shutDown method call, called immediately block waiting awaitTermination method, thereby generating a synchronizing effect.

 

About Executors

  Executors see the source code, we can see that there are many internal static methods, you can create a variety of thread pool. Therefore, in the actual code development, we often use the Executors of static factory method to create a thread pool, there are four common thread pool.

  1. newFixedThreadPool (using LinkedBlockingQueue queue - based chain blocking queue) fixed-length thread pool, as the name suggests, to create the largest number of parameters of the thread, when the maximum number, the size of the thread pool will not change.
  2. newCachedThreadPool (SynchronousQueue using synchronous queue) can be cached thread pool, the flexibility to create, flexible recovery.
  3. newScheduledThreadPool (using DelayedWorkQueue delay queue) Support regular and periodic tasks, like Quartz and Timer.
  4. newSingleThreadExecutor (using LinkedBlockingQueue queue - based chain blocking queue) single-threaded thread pool, it will only create a thread to perform the task, the task can be performed in a specified order, such as FIFO, priority, etc.

 

Guess you like

Origin www.cnblogs.com/Demrystv/p/11514847.html