Multi-thread (concurrency) for Java from single-core to multi-core)

Source: Internet
Author: User

Multi-thread (concurrency) for Java from single-core to multi-core)
Java's parallel programming is complicated and I cannot understand it deeply. However, due to the need to train the classifier in parallel recently, I thought about it. please correct me if you have any errors. This is just a general introduction. Many problems can be solved using sequential programming. However, if you can execute tasks in parallel with multiple threads, the time efficiency can be greatly improved. Therefore, multithreading is necessary. I have summarized three stages of development in JAVA parallelism (cainiao's summary, please be considerate) Phase 1: Thread, Runable Phase 2: Executor framework Phase 3: the concurrency of the ForkJoin parallel framework is very high. One aspect is to improve the program running speed. If you want a program to run faster, you can divide it into multiple fragments, then, multiple tasks are run on each independent processor. Now we should master the multi-core era, but we know that concurrency is usually used to improve the performance of the Single-core machine program. This is a bit incomprehensible to anyone who has learned the operating system, switching from one task to another may incur context overhead. However, with blocking, this problem is somewhat different. "Blocking" usually refers to a task of a program, because it is not necessary to execute the program control, such as requesting I/O resources, because it needs to wait for the requested I/O resources, so the program will be suspended, that is, the cpu is idle. We know that cpu is a very valuable resource and we should make full use of it. At this time, multithreading will come out. Think about it. When a thread is blocked, the cpu will be idle, at this time, the operating system allocates the cpu to other waiting threads so that the cpu is running all the time. A single process can have multiple concurrent tasks. We feel like each task has its own cpu. Its underlying mechanism is to split the cpu time. Generally, we don't need to worry about it. In fact, if the program is not congested, The concurrency on a single processor is meaningless. (1) traditional concurrent programming (Thead and Runable) We can see that the most is to inherit the Thread class or inherit the Runable interface. Both methods can be used as follows: copy the code public class App {public static class demo extends Thread {int x; public demo (int x) {this. x = x;} public void run () {System. out. print ("Thread" + x) ;}} public static void main (String [] args) {demo dem = new demo (1); dem. start () ;}} copy the Code, whether it is Thread or Runable, as long as we overwrite the Run method, however, since java classes can only inherit once and there are countless interfaces, we often use Ruanble interfaces. We use the start () method instead of the run () method to call the new thread. The essence of the start method: Apply for another thread space from the cpu to execute the run method. This is a concurrent thread. (In fact, it will also call the methods in the run, but if we call the run method directly, it will be a single thread.) Although the above two methods can implement the Basic parallel structure, however, complicated problems will be very troublesome, so we have the Excutor actuator introduced in JDK 5. (2) Executor framework refers to some executor-related function classes in a series of concurrent libraries introduced in java 5, including thread pools, Executor, Executors, ExecutorService, CompletionService, and Future, callable. Executor is used to manage the execution of Runable objects. The Thread used to create and manage a set of Runable objects. This set of threads is called the Thread pool route cute (Runnalbe ). Executor uses an internal thread pool to complete operations during execution. Thread t1 = new Thread (s1); Thread t2 = new Thread (s2); Thread t3 = new Thread (s3); ExecutorService service = Executors. newCachedThreadPool (); service.exe cute (t1); service.exe cute (t2); service.exe cute (t3); In Executor. We can use Callable and Future to return results. Future <V> indicates an asynchronous operation. The get () method can be used to obtain the operation result. If the asynchronous operation is not completed, get () will block the current thread. FutureTask <V> implements Future <V> and Runable <V>. Callable indicates an operation with a return value. Copy the code ThreadPoolExecutor myExecutor = new ThreadPoolExecutor (3, 10,200, TimeUnit. SECONDS, new LinkedBlockingDeque <Runnable> (); List <Future <ArrayList <Integer> results = new ArrayList <Future <ArrayList <Integer> (); for (int I = 0; I <3; I ++) {ACO task = new ACO task (choose); Future <ArrayList <Integer> result = null; result = myExecutor. submit (task); results. add (result);} // ExecutoreService For the submit () method, pass a Callable or Runnable, and return the Future. // If the Executor background thread pool has not completed Callable calculation, this calls the get () method of the Future object, will block until the calculation is complete for (Future <ArrayList <Integer> f: results) {try {f. get ();} catch (Exception ex) {// ex. printStackTrace (); f. cancel (true) ;}} it is good to copy the code and execute it concurrently, but there is a problem. The execution of different threads is slow, and some tasks are completed early. Therefore, a work-stealing algorithm is used to use these threads. (3) The ForkJoin parallel framework Fork/Join framework is a framework provided by Java 7 for parallel task execution. It is a framework that divides large tasks into several small tasks, A framework that summarizes the results of each small task and obtains the results of a large task. Is it like map/reduce. The Fork/Join mode has its own applicability. If an application can be divided into multiple subtasks and combined with multiple subtasks, the final answer is obtained. Therefore, this application is applicable to the Fork/Join mode. ForkJoin is a recursive decomposition of a problem into a subproblem, and then a parallel operation of the subproblem is performed to merge the results. Let's use the Fork/Join framework with a simple requirement: Calculate the result of 1 + 2 + 3 + 4. To use the Fork/Join framework, we must first consider how to split the task. If we want to add up to two counts for each subtask, we set the split threshold to 2, the Fork/Join framework will fork the task into two subtasks. subtask 1 is responsible for computing 1 + 2, and subtask 2 is responsible for computing 3 + 4, then join the results of the two subtasks. Because the task has a result, the RecursiveTask must be inherited.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.