Java multi-threaded (concurrency) from single core to multicore

Source: Internet
Author: User

JAVA concurrency

Parallel programming in Java is complicated, and I don't understand it deeply. But recently, due to the parallel training of classifiers, pondering a little, there are errors please correct me. Just a rough introduction.

Many problems we use sequential programming can be solved, but some problems if you can use multi-threaded parallel execution of the task of which can greatly improve the time efficiency, so multithreading is still very necessary.

I myself summed up the Java Parallel 3 development stages (rookie summary, please understand)

First stage: Thread, runable

Phase II: Executor framework

Phase III: forkjoin parallel Framework

Concurrency is large on the one hand to improve the speed of the program, if you want a program to run faster, you can split it into multiple fragments, and then run multiple tasks on each individual processor. Now is the multicore age we should master,

but we know that concurrency is often used to improve the performance of a single-core machine program, which is a bit incomprehensible to listen to, the person who learned the operating system should know that from one task to another task is a contextual cost. but because of the " blocking ", it makes the problem a little bit different.

"Blocking" usually refers to a task of a program due to the execution of something other than program control, such as requesting I/O resources, because I need to wait for the requested I/O resources, it will cause the program to pause, that is, CPU idle. We know that the CPU is a very valuable resource, we should make full use of it, when the multithreading comes out, think Ah, when a thread blocking causes the CPU idle, this time the operating system will allocate the CPU to other waiting threads so that the CPU is running all the time. A single process can have multiple concurrently executed tasks, and we feel as if each task has its own CPU, and its underlying mechanism is to slice the CPU time, usually without our tubes.

in fact, if the program does not have any blocking, then concurrency on a single processor is meaningless.

(1) Traditional concurrent programming (Thead, runable)

The most we see is inheriting the thread class or inheriting the Runable interface. Both of these are possible, inheriting the thread as follows:

 Public classApp { Public Static classDemoextendsThread {intx;  PublicDemointx) { This. x=x; }         Public voidrun () {System.out.print ("Threads" +x); }     }     Public Static voidMain (string[] args) {demo Dem=NewDemo (1);                   Dem.start (); }}

Whether it is thread or runable, as long as we overwrite the implementation of the Run method is good, but because the Java class can only inherit once and the interface can have countless, so we use the Ruanble interface more often. We call the new thread using the start () method instead of the run () method.

The essence of the Start method: request Another thread space from the CPU to execute the Run method, which is a concurrent thread. (It's also a way to invoke run itself, but if we call the Run method directly, then it's a single thread.)

Although the above two can achieve the basic parallel structure, but for the complex problems will be very cumbersome, so there is the introduction of JDK5 inside the excutor actuator.

(2) Executor frame

The Executor framework refers to a number of Executor-related functional classes in a series of concurrency libraries introduced in Java 5, including the thread pool, Executor,executors,executorservice,completionservice, Future,callable and so on.

Executor is used to manage the execution of Runable objects. A thread used to create and manage a set of Runable objects called the thread pool (thread pool)

A programming method for concurrent programming is to split the task into columns of small tasks, namely runnable, and then commit to a Executor execution,executor.execute (runnalbe) . The executor uses the internal thread pool to complete the operation at execution time.

                Thread T1 =new thread (S1);          Thread T2 =new thread (s2);          thread t3 =new thread (S3);          Executorservice service = Executors.newcachedthreadpool ();          Service.execute (t1);                  Service.execute (T2);                 

Inside the executor. We can use callable,future to return results,future<v> represents an asynchronous operation, the Get () method can get the result of the operation, and if the asynchronous operation has not yet completed, then get () will cause the current thread to block. The futuretask<v> implements Future<v> and runable<v>. Callable represents one with a return worth operation.

Threadpoolexecutor Myexecutor =NewThreadpoolexecutor (3, 10, 200, Timeunit.seconds,NewLinkedblockingdeque<runnable>()); List<Future<ArrayList<Integer>>> results =NewArraylist<future<arraylist<integer>>>();  for(inti = 0; I < 3; i++) {Acotask task=NewAcotask (choose); Future<ArrayList<Integer>> result =NULL; Result=Myexecutor.submit (Task);        Results.add (result); }                //Executoreservice provides the Submit () method, passing a callable, or runnable, back to the future. //if the executor background thread pool has not completed callable calculations, this call returns the Get () method of the future object, blocking until the calculation is complete         for(future<arraylist<integer>>f:results) {            Try{f.get (); } Catch(Exception ex) {//ex.printstacktrace ();F.cancel (true); }        }

The above concurrency is pretty good, but there's a problem. Different threads perform a block with slow, some tasks are executed early, so a work-stealing (work-stealing) algorithm is used to take advantage of these early-executed threads.

(3) Forkjoin parallel frame

The Fork/join framework is a framework that JAVA7 provides for parallel execution of tasks, a framework that divides large tasks into small tasks, and ultimately summarizes the results of a large task after each small task. is not much like map/reduce.

Fork/join mode has its own scope of application. If an application can be decomposed into multiple subtasks, and the result of combining multiple sub-tasks is able to get the final answer, then this application is suitable to be solved with Fork/join mode. Forkjoin is the recursive decomposition of a problem into sub-problems, and then the sub-problem parallel operation after merging results.

Let's use the next Fork/join framework with a simple requirement: to calculate the results of 1+2+3+4.

The first thing to consider when using the Fork/join framework is how to split the task, and if we want each subtask to perform up to two numbers, then we set the split threshold to 2, because 4 numbers are added, so the Fork/join framework will fork this task into two subtasks, Subtask one is responsible for calculating 1+2, sub Task Two is responsible for calculating the 3+4, and then join two subtasks results.

Because it is a result of the task, so must inherit Recursivetask.

We only need to focus on sub-task partitioning and the combination of intermediate results. Forkjointask completes the sub-task partition and submits it to the Forkjoinpool to complete the application.

Code for Fork/join View: http://blog.csdn.net/lubeijing2008xu/article/details/18036931

Http://www.oracle.com/technetwork/cn/articles/java/fork-join-422606-zhs.html

http://www.ibm.com/developerworks/cn/java/j-lo-forkjoin/

Java multi-threaded (concurrency) from single core to multicore

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.