Java High concurrency Programming (iv)

Source: Internet
Author: User
Tags stream api

First, executor actuator

1.Executor interface, the top-level interface in the Java thread Pool framework, provides an Execute method to perform tasks

ImportJava.util.concurrent.Executor; Public classT01_myexecutorImplementsExecutor { Public Static voidMain (string[] args) {NewT01_myexecutor (). Execute (()->system.out.println ("Hello executor")); } @Override Public voidExecute (Runnable command) {//new Thread (command). Run ();//Another thread method callCommand.run ();//method calls directly    }}

2. Task interface

1) Callable Interface: Provides a call method with a return value that can throw an exception

2) Runnable interface: Provides a run method, no return value non-throwing exception

3.ExecutorService Interface (one sub-interface of executor)

1) Executorservice can be understood as a service, executing the Execute method can add runnable tasks to the server without a return value, while the Execute Submit method can add callable and runnable tasks to the service with a return value

2) Executor and Executorservice's simple understanding: You can imagine that many executor executor are waiting to perform tasks, and service service can add different tasks by invoking the Execute or Submit method for executor execution

3) The Submit method has a return value of the future type, which is used with callable,executors

 Public classT06_future { Public Static voidMain (string[] args)throwsinterruptedexception, executionexception {futuretask<Integer> task =NewFuturetask<> ((){TimeUnit.MILLISECONDS.sleep (500); return1000; }); //New Callable () {Integer call ();}                NewThread (Task). Start (); System.out.println (Task.get ()); //Blocking//*******************************Executorservice service = Executors.newfixedthreadpool (5); Future<Integer> f = service.submit ((){TimeUnit.MILLISECONDS.sleep (500); return1;        });        System.out.println (F.get ());            System.out.println (F.isdone ()); }}

Operation Result:

4.Executors (a tool class for Operation executor, factory Class)

Second, threadpool thread pool

1. The thread pool assigns the task to the thread in the pool, and when threads are not executing, the task goes into the wait queue, which is implemented by Blockingqueue, which is assigned to the idle thread when it comes to the task when it is idle, and one thread maintains both queues (end queue and wait queue)

The following program helps to understand the thread pool concept

 Public classT05_threadpool { Public Static voidMain (string[] args)throwsinterruptedexception {executorservice service= Executors.newfixedthreadpool (5);//Execute Submit         for(inti = 0; I < 6; i++) {Service.execute ()- {                Try{TimeUnit.MILLISECONDS.sleep (500); } Catch(interruptedexception e) {e.printstacktrace ();            } System.out.println (Thread.CurrentThread (). GetName ());        });                } System.out.println (service); Service.shutdown ();//gracefully shuts down, waits for all tasks to complete, closes the thread poolSystem.out.println (service.isterminated ());//Judging if all the tasks are done .System.out.println (Service.isshutdown ());//determine if the thread pool is closedSystem.out.println (service); TimeUnit.SECONDS.sleep (5);        System.out.println (service.isterminated ());        System.out.println (Service.isshutdown ());    SYSTEM.OUT.PRINTLN (service); }}

Operation Result:

2. Six kinds of thread pools

1) fixedthreadpool thread pool with fixed number of threads

2) Cachedthreadpool assume that just starting a thread is not, to a task to open a thread, if another task, the thread pool has an idle thread to assign the task to the idle thread, so back and forth until the computer can support the limit, the default one thread idle more than a minute to automatically destroy

3) Only one thread in the Singlethreadpool thread pool

4) Scheduledthreadpool Timer thread pool

5) Workstealingpool work to steal the thread pool, the current thread pool thread idle, will automatically go to find the task execution, by default, according to the number of CPU cores to start the default thread number of threads, is the wizard (demon) thread (daemon, background thread), the main function is not blocked to see the output, is essentially forkjoinpool implementation.

6) Forkjoinpool Fork Merge thread, large task can be cut into a lot of small tasks, if the small task is too large, you can continue to divide, points can be a small task to merge, and finally produce a total result (a bit like merge sort)

Forkjointask inherit from Recursiveaction and Recursivetask

A.recursiveaction no return value

/*** Sum of all numbers in an array *@authorZhangqi **/ Public classT12_forkjoinpool {Static int[] Nums =New int[1000000]; Static Final intMax_num = 50000; StaticRandom r =NewRandom (); Static {         for(inti=0; i<nums.length; i++) {Nums[i]= R.nextint (100); } System.out.println (Arrays.stream (nums). sum ()); //Stream API    }            Static classAddTaskextendsrecursiveaction {intstart, end; AddTask (intSinte) {start=s; End=e; } @Overrideprotected voidCompute () {if(End-start <=max_num) {                Longsum = 0L;  for(intI=start; i<end; i++) sum + =Nums[i]; System.out.println ("From:" + Start + "to:" + end + "=" +sum); } Else {                            intMiddle = start + (End-start)/2; AddTask SubTask1=Newaddtask (start, middle); AddTask SubTask2=Newaddtask (middle, end);                Subtask1.fork ();            Subtask2.fork (); }                                }            }            /*Static class AddTask extends recursivetask<long> {int start, end;            AddTask (int s, int e) {start = s;        end = e; } @Override protected Long Compute () {if (End-start <= max_num) {L                Ong sum = 0L;                for (int i=start; i<end; i++) sum + = Nums[i];            return sum;                        } int middle = start + (End-start)/2;            AddTask subTask1 = new AddTask (start, middle);            AddTask subTask2 = new AddTask (middle, end);            Subtask1.fork ();                        Subtask2.fork ();        return Subtask1.join () + Subtask2.join (); }            }*/         Public Static voidMain (string[] args)throwsIOException {forkjoinpool FJP=NewForkjoinpool (); AddTask Task=NewAddTask (0, nums.length);        Fjp.execute (Task); //Long result = Task.join (); //System.out.println (result);System.in.read (); }}

Operation Result:

B.rescursivetask recursive task with return value

/*** Sum of all numbers in an array *@authorZhangqi **/ Public classT12_forkjoinpool {Static int[] Nums =New int[1000000]; Static Final intMax_num = 50000; StaticRandom r =NewRandom (); Static {         for(inti=0; i<nums.length; i++) {Nums[i]= R.nextint (100); } System.out.println (Arrays.stream (nums). sum ()); //Stream API    }        /*Static class AddTask extends Recursiveaction {int start, end;            AddTask (int s, int e) {start = s;        end = e; } @Override protected void Compute () {if (End-start <= max_num) {L                Ong sum = 0L;                for (int i=start; i<end; i++) sum + = Nums[i];            System.out.println ("From:" + Start + "to:" + end + "=" + sum);                                } else {int middle = start + (End-start)/2;                AddTask subTask1 = new AddTask (start, middle);                AddTask subTask2 = new AddTask (middle, end);                Subtask1.fork ();            Subtask2.fork (); }                                }            }*/            Static classAddTaskextendsRecursivetask<long> {                 intstart, end; AddTask (intSinte) {start=s; End=e; } @OverrideprotectedLong Compute () {if(End-start <=max_num) {                Longsum = 0L;  for(intI=start; i<end; i++) sum + =Nums[i]; returnsum; }                         intMiddle = start + (End-start)/2; AddTask SubTask1=Newaddtask (start, middle); AddTask SubTask2=Newaddtask (middle, end);            Subtask1.fork ();                        Subtask2.fork (); returnSubtask1.join () +Subtask2.join (); }            }         Public Static voidMain (string[] args)throwsIOException {forkjoinpool FJP=NewForkjoinpool (); AddTask Task=NewAddTask (0, nums.length);        Fjp.execute (Task); Longresult =Task.join ();                SYSTEM.OUT.PRINTLN (result); //System.in.read ();            }}

Operation Result:

Add:

Threadpoolexecutor thread pool Executor (custom thread pooling, the underlying implementation of many thread pools, Forkjoinpool not implemented by it)

Java High concurrency Programming (iv)

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.