Threadpool for Java Multithreading

Source: Internet
Author: User

The usage of common thread pools and thread pools with returned values is demonstrated here.

Package COM. jadyer. thread. pool; import Java. util. random; import Java. util. concurrent. callable; import Java. util. concurrent. completionservice; import Java. util. concurrent. executionexception; import Java. util. concurrent. executorcompletionservice; import Java. util. concurrent. executorservice; import Java. util. concurrent. executors; import Java. util. concurrent. future; import Java. util. concurrent. timeunit;/*** th Readpool test * @ see ======================================== ========================================================== ===================================* @ see the difference between a thread and a process * @ see 1) the internal data and status of multiple processes are completely independent, while multithreading shares a piece of memory space and a group of system resources, which may affect each other * @ see 2) the data of the thread is usually only the register data and the stack used when a program is executed. Therefore, thread switching is less costly than process switching * @ see ========================== ========================================================== ============================================= * @ see Thread Startup Mode and extinction * @ see 1) take thread. when start () is started, JVM will run it as a thread. Start () first prepares system resources for thread execution, and then calls the run Method * @ see 2. when run () is started, JVM runs it in a common method. At this time, there will be no effect of thread-specific alternate execution * @ see 3) When two objects of a Thread class are running in the START () mode, the JVM will still treat them as two thread classes to execute * @ see 4) when terminating the thread, the STOP () method is absolutely not allowed, but should let run () natural end * @ see ====================================================== ========================================================== =================================* @ author macro Yu * @ create Feb 29,201 2 1:13:43 am */public class threadpooltest {public static void main (string [] ARGs) {New threadpooltest (). threadpooltest (); New threadpooltest (). Threadpoolscheduledtest (); New threadpooltest (). threadpoolcallbaleandfuturesigntest (); New threadpooltest (). threadpoolcallbaleandfuturemoretest ();}/*** several ways to create a thread pool * @ see executors. newfixedthreadpool (3); // create a fixed thread pool * @ see executors. newcachedthreadpool (); // create a cache thread pool. It dynamically creates a thread * @ see executors. newsinglethreadexecutor (); // creates a single thread pool based on the number of actually requested threads. It can achieve the effect of restarting when the thread dies, but the actual startup is "substitute thread" */Public void threadpooltest () {// newsinglethreadexecutor, if the thread in the pool is dead, it puts a "substitute thread" on the top, that is, it ensures that there is always a thread in the pool that exists executorservice threadpool = executors. newsinglethreadexecutor (); For (INT I = 1; I <= 10; I ++) {final int task = imo-threadpool.exe cute (New mythread (task )); // note that execute () returns void} system. out. println ("all of 10 tasks have committed ...... "); // after all tasks in the thread pool are executed, close the threadpool of the thread pool. Shutdown ();}/*** thread pool startup timer * @ see executors. newscheduledthreadpool (3 ). schedule (); // create and execute one-time operations enabled after a given delay * @ see executors. newscheduledthreadpool (3 ). scheduleatfixedrate (); // After the instance is started for the first time, the operation is automatically executed at a fixed frequency * @ see scheduleatfixedrate (). It supports the time interval for repeated tasks, but does not directly support absolute time, we need to convert to relative time to execute */Public void threadpoolscheduledtest () {// automatically execute once in 10 seconds // executors. newscheduledthreadpool (3 ). schedule (New myscheduledthread (), 10, timeuni T. seconds); // execute it for the first time after 6 seconds, and executors is automatically executed every 2 seconds. newscheduledthreadpool (3 ). scheduleatfixedrate (New myscheduledthread (), 6, 2, timeunit. seconds);}/*** the thread pool returns the value of a task * @ See note: Java is required here. util. concurrent. executorservice. submit () to submit, it will return the future object * @ See note: the type of the result obtained by future, which must be consistent with the result type returned by callable. Here we implement */Public void threadpoolcallbaleandfuturesigntest () {executorservice threadpool = executors through generics. newsinglethreadexecutor (); Future <string> future = threadpool. submit (New callable <string> () {@ overridepublic string call () throws exception {thread. sleep (2000); Return "Zhang qiling" ;};}); system. out. println ("waiting for results"); try {system. out. println ("Get Result:" + future. get (); // future. get (4, timeunit. seconds)} catch (I Nterruptedexception e) {e. printstacktrace ();} catch (executionexception e) {e. printstacktrace () ;}}/*** the thread pool returns the value of multiple tasks * @ see Java. util. concurrent. completionservice is used to submit a set of callable tasks * @ see completionservice. take () will return the future object corresponding to a completed callable task * @ see, which is like planting a few vegetable plots at the same time and waiting for receiving food. When receiving food, which dish is cooked, you should first collect the vegetable dish */Public void threadpoolcallbaleandfuturemoretest () {executorservice threadpool = executors. newfixedthreadpool (5); completionservice <integer> completionservice = new executorcompletionservice <integer> (threadpool); For (INT I = 1; I <= 5; I ++) {final int taskcode = I; completionservice. submit (New callable <integer> () {@ overridepublic integer call () throws exception {thread. sleep (new random (). nextint (5000); Return taskcode ;}}) ;}for (INT I = 0; I <5; I ++) {try {system. out. println (completionservice. take (). get ();} catch (interruptedexception e) {e. printstacktrace ();} catch (executionexception e) {e. printstacktrace () ;}}} class mythread implements runnable {private integer task; Public mythread (integer task) {This. task = task;} @ overridepublic void run () {// you do not need to write J here because it is used with for () in threadpooltest () I in a loop is not a variable in the same method, so it does not conflict with for (INT I = 1; I <= 10; I ++) {try {thread. sleep (20);} catch (interruptedexception e) {e. printstacktrace ();} system. out. println (thread. currentthread (). getname () + "is looping of" + I + "for task of" + task) ;}} class myscheduledthread implements runnable {@ overridepublic void run () {system. out. println ("bombing ...... ");}}

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.