Multi-threaded programming (1)

1. processes and threads

  Typically, a job is a process (Process), such as opening a browser is a browser launch process, to open a Word started the process a Word. Most of the time a process need to do many things, such as Word, it can be carried out simultaneously typing, spell checking, printing and other things. Within a process, and more things to be doing at the same time, you need to run multiple "sub-tasks", we put these "sub-tasks" in the process is called a thread (Thread). That is a program of at least one process, a process has at least one thread .

  We UNIVERSITY operating system, they both know that the process is the basic unit of resource allocation, the thread is the basic unit of execution and scheduling, thread itself does not have the resources, resources from its process. That is, during execution process has its own memory space, separated from each other with other processes, and therefore into the communication path between the need to open a new path, a duct such as common communication, message queues, semaphores, and the like sockets, Meanwhile, a process has three large - process control block (the PCB), the data segment, code segments, which leads to a large overhead will have inter-process. Because the shared memory region communication between application processes and threads the thread, which may be between one another, because of the small size of the thread, so that the switching speed is much faster than thread process, can greatly improve the efficiency of the program, as described below, the thread is and the process of relationship (picture taken from the known almost ).

  Divided into two threads: the user thread and thread guard. Daemon thread, refers to the provision of a universal service in the background when the program is running threads, such as garbage collection thread is the guardian of a very competent, and this thread does not belong to an integral part of the program. Daemon thread is used to service user thread, once the user thread running all over, the program terminates, the guardian of the thread will also exit.

  Before entering the multi-threaded, you can take a look at several state of the thread:

  • 1. New (NEW) : create a new thread object.
  • 2. Ready (RUNNABLE or READY) : threads are participating in the competition the right to use the CPU.
  • 3. Run (the RUNNING) : Take the thread to the right to use the CPU, is executed.
  • 4. blocked (BLOCKED) : the thread is blocked for some reason to give up the right to use CPU temporarily stops running. Until the condition is met (such as a timeout waiting, wake-up), the thread back to the ready state, competing CPU usage rights.
  • 5. wait for (the WAITING) : thread to wait indefinitely lock an object, or wait for another thread to the end of the state.
  • 6. Timing wait (TIME_WAITING) : thread waits for an object in a certain period of time "lock", or active sleep, or by waiting for the end of a thread, unless interrupted, time is up, immediately return to the ready state, is interrupted the method throws an exception.
  • 7. termination (Terminated) : That thread to terminate (the code of the thread is finished) and execution abnormal or forcibly interrupted by the outside world.

The specific transformation state transition as shown below:

2. Thread class and Runnable interface

  It can be realized by a thread class Thread class inheritance, real run method, commonly used API as follows:

  The method described
start() New state transition from the ready state, began to participate in the competition the right to use the CPU.
run() Direct access to the right to use the CPU when the direct call that Runnable object's run method
interrupt() Interrupt thread. In the program code with the while (! Thread.interrupted ()) {..} use.
isDaemon() Determining whether the current thread is a daemon thread.
setDaemon(boolean true) Set the current thread as a daemon thread, must be effective after calling start ().
setPriority(int priority) Change the priority of the thread.
interrupt() Interrupt thread.
isAlive() Tests if this thread is active.
join(long millisec) Wait for this thread to a maximum of millis milliseconds.
Thread.yield() Suspend the currently executing thread object (let the current thread CPU, into a ready state), and perform other threads.
Thread.currentThread() It returns a reference to the currently executing thread object is.
Thread.sleep(long millisec) The currently executing thread to sleep in a specified number of milliseconds (suspended), this subject and accuracy of system timers and schedulers accuracy.

  Because of java in the class is a single inheritance, multiple inheritance and interface. Case a class implements multiple interfaces, because the interface is only abstract methods, specific methods can only be achieved by the implementation of the interface class, method implementation class will always call (there is no ambiguity) at the time of the call, it is often used in the development of Runnable.

public class Thread1 implements Runnable {
    @Override
    public void run() {
        System.out.println("iii");
    }
​
    public static void main(String[] args) {
        Thread1 rt = new Thread1();
        Thread t = new Thread(rt);
        t.start();
    }
}

3. Thread Pool

  Threads at a time when a lot of creation and destruction will consume a lot of resources, we can create some threads in advance, they will be centrally managed to form a thread pool, when you need to use to take over the direct use, after use, put back to the thread pool.

Executor framework

  In java.util.cocurrent packet, controlled by the frame start thread, and performs closed, concurrent programming operation can be simplified, created by five Executors class static factory method, which is a common method as follows.

3.1 Creating a thread pool

  1. newFixedThreadPool: create a thread pool of fixed size. Once the size of the thread pool reaches the maximum will remain unchanged, because if a thread execution abnormal end, the thread pool would add a new thread.

    The Executors class {public 
        / * 
        Function: thread pool that creates a fixed length, blocking queue for storing task LinkedBlockingQueue unlimited length. Thread pool thread will always exist unless the thread pool shutdown, ie the threads in the pool is not limited survival time. 
        * / 
        Public static ExecutorService newFixedThreadPool (int nThreads) { 
           / * parameter number of threads a core size (the minimum number of threads), when the number of threads <a parameter, will create threads execute Runnable 
            * parameter maximum number of threads Second, when the number of threads > = parameter II will runnable into workQueue (parameter 5) 
            * three parameters to maintain the survival time, the maximum time to maintain the idle threads. 
            * Parameter four times the unit 
            * Save task parameters five blocking queue 
            * public ThreadPoolExecutor (corePoolSize int, 
                                  int maximumPoolSize, 
                                  Long keepAliveTime, 
                                  TimeUnit Unit, 
                                  BlockingQueue <Runnable> workQueu 
            * / 
                return the ThreadPoolExecutor new new (nThreads1, nThreads2, 
                                              0L, TimeUnit.MILLISECONDS, 
                                              new new a LinkedBlockingQueue <the Runnable> ()); 
        } 
        // ... 
    } 
    ExecutorService ES = Executors.newFixedThreadPool (20 is); 
    // If the thread the number of threads in the pool is too large or too small, will affect performance
  2. newCachedThreadPool: Create a cache of 60 seconds of idle threads the thread pool. If the size of the thread pool threads exceeds the processing tasks required, it will recover partially free (60 seconds does not perform the task) threads, when the number of tasks, this thread pool and intelligently add a new thread to handle the task.

    the Executors class {public     
        public static ExecutorService newCachedThreadPool () { 
                return new new the ThreadPoolExecutor (0, Integer.MAX_VALUE, 
                                              60L, TimeUnit.SECONDS, 
                                              new new SynchronousQueue <the Runnable> ()); 
         } 
        // ...    
    } 
    ExecutorService ES = Executors.newCachedThreadPool (); 
    // drawback is the traffic suddenly a lot of time, it will create a large number of threads
  3. Creating a single-threaded thread pool. This is only a thread pool thread work, which is equivalent to a single-threaded serial execution of all tasks. If this thread only because of abnormal termination, then there will be a new thread to replace it.

    ExecutorService es = Executors.newSingleThreadExecutor();
    //等同于 ExecutorService es = Executors.newFixedThreadPool(1);
  4. newScheduledThreadPool: Create an unlimited size of the thread pool. This thread pool to support the timing and the need to perform tasks periodically.

    static void main public (String [] args) { 
            The ScheduledExecutorService Executors.newScheduledThreadPool SES = (. 1); 
            ses.scheduleWithFixedDelay (the Runnable new new () { 
                @Override 
                public void RUN () { 
                    the try { 
                        the Thread.sleep (3000); 
                    } the catch ( E InterruptedException) { 
                        e.printStackTrace (); 
                    } 
                    System.out.println (new new a Date ()); 
                } 
            }, 1000 / * start of a first cycle time * /, 2000 / * time interval of each cycle * / , TimeUnit.MILLISECONDS); 
        }
  5. newSingleThreadScheduledExecutor: create a thread pool of single-threaded. This thread pool to support the timing and the need to perform tasks periodically.

3.2 using threads in the thread pool

  Executors class to get through the thread pool ExecutorService have achieved this interface. You can call the execute () or submit () method to submit to the appropriate task to the thread pool.

 1. Execute (Runnable): This method receives a Runnable example, and asynchronous execution.

public static void main(String[] args) {
        ExecutorService es = Executors.newCachedThreadPool();
//        Future future =
        es.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("run the thread.");
            }
        });
        System.out.println("over");
 }
/* output:
 * over
 * run the thread.
 */

2. the Submit (Runnable): submit(Runnable)and execute(Runnable)the difference is that the former can return a Future object, Future returned object, we can check whether the submitted task is finished.

static void main public (String [] args) throws ExecutionException, InterruptedException { 
        ExecutorService Executors.newCachedThreadPool ES = (); 
        Future Future = es.submit (the Runnable new new () { 
            @Override 
            public void RUN () { 
                the try { 
                    the Thread.sleep ( 1000); 
                } the catch (InterruptedException E) { 
                    e.printStackTrace (); 
                } 
                System.out.println ( "The Thread RUN."); 
            } 
        }); 
        Future.get (); //future.get () method will generating block until completion of the above threads, i.e., wait a second 
        System.out.println ( "over"); 
} 
/ * Output: 
 * the RUN thread.
 * over
 */

3. Submit (Callable): submit(Callable)and submit(Runnable)the like, also returns a Future object, the method of call parameters Callable class can return a value, and not Runable.

public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService es = Executors.newCachedThreadPool();
        Future future = es.submit(new Callable() {
            @Override
            public Object call() throws Exception {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return "run the thread.";
            }
        });
        String rs = (String)future.get();  //future.get()方法会产生阻塞
        System.out.println("over and " + rs);
 }
/* output:
 * over and run the thread.
 */

InvokeAny 4. (Collection <the extends Callable? <T> Tasks>>): Method Callable input receiving a set of parameter types, the plurality of task threads start to execute the corresponding independent thread, once a thread has finished, it returns while other threads to terminate.

public static void main(String[] args) throws ExecutionException, InterruptedException {
​
        ExecutorService es = Executors.newFixedThreadPool(3);
​
        Set<Callable<String>> callables = new HashSet<Callable<String>>();
​
        callables.add(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(2000);
                return " first task";
            }
        });
​
        callables.add(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(1000);
                return " second task";
            }
        });
​
        callables.add(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(3000);
                return " third task";
            }
        });
​
        String rs = es.invokeAny(callables);
        System.out.println(rs);
}
​
/* output
 * second task
 */

To invokeAll 5. The (Collection <the extends Callable? <T> : Tasks>>) all methods which will be performed in parallel Callable collection type.

public static void main(String[] args) throws ExecutionException, InterruptedException {
​
        ExecutorService es = Executors.newFixedThreadPool(3);
​
        Set<Callable<String>> callables = new HashSet<Callable<String>>();
​
        callables.add(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(2000);
                return " first task";
            }
        });
​
        callables.add(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(1000);
                return " second task";
            }
        });
​
        callables.add(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(3000);
                return " third task";
            }
        });
​
        List<Future<String>> list= es.invokeAll(callables);
        for (Future<String> future:list) {
            String s = future.get();
            System.out.println(s);
        }
}

6. shotdown (): After calling this method, the thread pool is closed, the method has been submitted will continue after the end of execution, the thread pool all closed, which is an asynchronous method, once the call returns immediately.

7.shotdownNow (): After calling this method, the thread pool is closed, the method has been submitted will be canceled, the thread pool immediate and complete closure, which is an asynchronous method, once the call returns immediately.

8. awaitTermination (timeout, unit): This method is called blocks the current thread, so that thread pool thread execution is completed, the maximum wait time for the timeout, this method requires effective only after calling shotdown / shotdownNow.

public class the ThreadSafe the implements the Runnable { 
    Private static int COUNT = 0; 
    @Override 
    public void RUN () { 
        for (int I = 0; I <10; I ++) { 
            COUNT ++; 
        } 
    } 
    public static void main (String [] args) throws {InterruptedException 
        ExecutorService ES = Executors.newFixedThreadPool (10); 
        for (int I = 0; I <20 is; I ++) { 
            es.execute (the ThreadSafe new new ()); 
        } 
        es.shutdown (); // not allowed to add thread, Close asynchronous connection pool 
        es.awaitTermination (10L, TimeUnit.SECONDS); // wait for completion of the task thread connection pool 
        System.out.println (COUNT); 
    } 
} 
/ * Output  
* 200 is
* /

references

  1. Pang Yonghua Java multi-threading and Socket:.. Combat micro-services framework [M] Electronic Industry Press .2019.3

  2. Several methods of analysis to create a thread pool Executors class

 

 

Guess you like

Origin www.cnblogs.com/helloworldcode/p/11715306.html