3.java and contract

Source: Internet
Author: User

1. Java and contract introduction

Later versions of JDK5.0 introduce advanced concurrency features, most of which are designed for multithreaded concurrent programming in the Java.util.concurrent package, leveraging modern multiprocessor

and multi-core system capabilities to write large-scale concurrent applications. It mainly contains atomic weight, concurrent set, Synchronizer, Reentrant Lock, and provides strong support for the construction of thread pool .

2. Thread Pool

The thread pool is a form of multithreading that adds tasks to the queue during processing, and then automatically starts those tasks after the thread is created

2.1.5 ways to create a thread pool

1. Single thread Executor: There is only one thread pool, so all committed tasks are executed sequentially

  Code: Executors.newsinglethreadexecutor ()

   2. Cached thread pool: There are many threads in the thread pool that need to be executed at the same time, the old available thread will be re-executed by the new task, and if the thread is not executed in more than 60 seconds, it will

is terminated and removed from the pool,

Code: Executors.newcachedthreadpool ()

  3. Fixed thread pool: A thread pool that has a fixed number of threads, and if no task is executed, the threads wait.

Code: Executors.newfixedthreadpool (4)

Parameter 4 in the constructor is the size of the thread pool, you can set it at will, or you can match the number of cores in the CPU,

Gets the number of cores of the CPU: int cpunums = Runtime.getruntime (). Availableprocessors ();

   4. Scheduled thread pool: The thread pool that is used to dispatch the task that is about to be executed, may not be executed directly, how often it is executed ... Strategy-based

Code: Executors.newscheduledthreadpool ()

   5. Single thread scheduled Pool: Only one thread is used to schedule a task to execute at a specified time, Code: Executors.newsinglethreadscheduledexecutor ()

2.2. Use of the thread pool

The usage of various thread pools in the contract and the mechanism of the future get task returning result

1. Submit Runnable, the future object returns null after the task is completed, and then call Excute, submit the task , anonymous runable rewrite run method , which is the business logic in the Run method

Package Cn.thread;import Java.util.concurrent.executorservice;import java.util.concurrent.executors;public Class Threadpoolwithrunable {    /**     * Executes threads through thread pool     * @param args     *    /public static void main (string[] args) {        //Create a thread pool        executorservice pool = Executors.newcachedthreadpool ();         < 5 ; i++) {            //Submit Task            Pool.execute (New Runnable () {                @Override public                void Run () {                    System.out.println (" Thread Name: "+ Thread.CurrentThread (). GetName ());                    try {                        thread.sleep;                    } catch (Interruptedexception e) {                        e.printstacktrace ();}}            );        }        Pool.shutdown ();    }}

2. Submit callable, the method returns a future instance representing the status of the task, invoking the submit submission task , anonymous callable, overriding the call method , have a return value , get the return value will block , have to wait

To the thread task to return the result

Package Cn.thread;import Java.util.arraylist;import java.util.list;import java.util.concurrent.callable;import Java.util.concurrent.executionexception;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import java.util.concurrent.future;/** * The difference between callable and runnable: * The runnable run method does not return any results, so the main thread cannot get the return value of the task threads * Callable's Call method can return results, but the main thread gets blocked when it is fetched and waits for the task thread to return to get the result * @author */public         Class Threadpoolwithcallable {public static void main (string[] args) throws Interruptedexception, Executionexception {                 Executorservice pool = Executors.newfixedthreadpool (4); for (int i = 0; I<Ten; i++)            {//Submit a return value task for execution, returning a future that represents the pending result of the task. Future<string>Submit = Pool.submit (New callable<String>() {@Override public String call () throws Exception {//SYSTEM.OUT.PR                    Intln ("a");                    Thread.Sleep (5000);                Return "b--" +thread.currentthread (). GetName ();            }                              });        From the future get results, this method will be blocked until the thread task returns the result System.out.println (Submit.get ());    } pool.shutdown (); }}

   

3.java and contract

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.