Java Multithreading using learning notes

Source: Internet
Author: User

Beginner Java Multi-threading, continuous improvement


One, callable

Callable are similar to runnable interfaces, classes that implement callable interfaces, and classes that implement runnable are tasks that can be performed by other threads

The differences between callable and runnable are as follows:

The method defined by 1.Callable is call, and the method defined by Runnable is run.

The 2.Callable call method can have a return value, and the runnable run method cannot have a return value.

The 3.Callable call method throws an exception, and the runnable run method cannot throw an exception.


Two, Executor



A, several different executorservice thread pool objects:

1. Newcachedthreadpool () Cache-type pool, first see if there are no previously established threads in the pool, and if so, reuse. If not, build a new thread into the pool, self-increment

2. Newfixedthreadpool (int var0) at any point in time, up to a fixed number of active threads, at this point, if a new thread is to be established, it can only wait in another queue until a thread in the current thread terminates and is removed directly from the pool.

3.SingleThreadExecutor () Single thread, only one thread can be in any time pool


4.ScheduledThreadPool () The thread in this pool can be executed by schedule, sequentially, or periodically.

Scheduledexecutorservice ThreadPool = Executors.newscheduledthreadpool (2); System.out.println ("Start Time" +new Date ()), Threadpool.schedule (New Myexecutor (), 2,timeunit.seconds); Threadpool.schedule (New Myexecutor (), 4,timeunit.seconds);


B,executorservice Interface Common methods:

1.void shutdown ()

This method turns off Executorservice smoothly, and when we call this method, Executorservice stops accepting any new tasks and waits for the committed task to complete (the tasks that have been submitted are divided into two categories: one is already executing, The other is not yet started) and will be closed when all the submitted tasks have been executed Executorservice

Executorservice service = Executors.newcachedthreadpool (); Service.submit (new Myexecutor ()); Service.shutdown ();

2.boolean isterminated (int timeout,timeunit unit)/booleanIsShutDown ()

This method has two parameters, one is timeout, and the other is unit-time units. This method causes the thread to wait for the timeout length, and when the timeout time is exceeded, it will monitor if the Executorservice is closed and returns true if closed, otherwise false. Typically used in combination with the Shutdown method

Executorservice executorservice= Executors.newcachedthreadpool (); Executorservice.submit (new MyExecutor ()); Executorservice.submit (New Myexecutor ()); Executorservice.submit (new Myexecutor ()); Executorservice.submit (new Myexecutor ()); Executorservice.shutdown (); System.out.println (executorservice.isterminated () + "-----" +executorservice.isshutdown ());


3.list<runnable> Shutdownnow ()

Method forces the shutdown of Executorservice, which cancels all running tasks and the tasks waiting in the work queue, which returns a list listing of tasks waiting in the work queue

Executorservice Service = Executors.newfixedthreadpool (3); Service.submit (new Myexecutor ()); Service.submit (new Myexecutor ()); Service.submit (new Myexecutor ()); Service.submit (new Myexecutor ()); list<runnable> runnables = Service.shutdownnow (); System.out.println ("Number of Waits:" +runnables.size ());

4.boolean awaittermination (long timeout, timeunit unit)

This method has two parameters, one is timeout, and the other is unit-time units. This method causes the thread to wait for the timeout length, and when the timeout time is exceeded, it will monitor if the Executorservice is closed and returns true if closed, otherwise false. Typically used in combination with the Shutdown method

Executorservice service = Executors.newcachedthreadpool (); Service.submit (new Myexecutor ()); Service.submit (new Myexecutor ()); Service.submit (new Myexecutor ()); Service.submit (new Myexecutor ()); Service.shutdown (); try {    while (!service.awaittermination (1, timeunit.seconds)) {        System.out.println ("thread pool is not closed");} SYSTEM.OUT.PRINTLN ("Thread pool has been closed");


Third, future

the future represents the result of an asynchronous calculation. It provides a way to check whether the calculation is complete, to wait for the completion of the calculation, and to retrieve the results of the calculation. The Futuretask class is an implementation of the future and implements the runnable, so it can be executed through the Excutor (thread pool), passed to the thread object, and generally futuretask for time-consuming computations. The main thread can get the results after completing its own tasks .


Common methods:

1.boolean Cancel (Boolean mayinterruptifrunning) attempted to cancel execution of this task. If the task is completed, canceled, or cannot be canceled for some other reason, the attempt will fail. When Cancel is called, if the call succeeds and the task has not been started, the task will never run. If the task is already started, the mayinterruptifrunning parameter determines whether the thread that performs this task should be interrupted in a way that attempts to stop the task. After this method returns, subsequent calls to IsDone () will always return true. If this method returns true, subsequent calls to iscancelled () will always return true

2.boolean iscancelled (): Returns True if the task is canceled before it is properly completed. if the Cancel method returns true, subsequent calls to iscancelled () will always return true

3.boolean IsDone (): Returns True if the task is completed. This method returns true in all of these cases, possibly due to a normal termination, exception, or cancellation.

4.V get () throws Interruptedexception,executionexception: Wait for the calculation to complete if necessary, and then get its results.

5.V Get (long timeout,timeunit unit) throws Interruptedexception,executionexception,timeoutexception: if necessary, Wait up to the time given for the calculation to complete, and obtain its result (if the result is available)

Class Pgpagemodelworker implements callable<integer> {private int shopid;public pgpagemodelworker (int shopid) { This.shopid = Shopid;} @Overridepublic Integer Call () throws Exception {Random rand = new Random (), int sleep=rand.nextint (+ 500;//thread.sl) Eep (sleep); int s = shopid + 1; System.out.println (shopid+ "Execution Time---" + sleep+ "milliseconds"); return s;}}


Class futuretask2test{public static void Main (string[] args) throws Interruptedexception {final Concurrenthash map<string, integer> modelmap = new concurrenthashmap<string, integer> (); final list<integer> Data=        Collections.synchronizedlist (New arraylist<integer> ());        Executorservice executor = Executors.newcachedthreadpool (); Final Countdownlatch countdownlatch = new Countdownlatch;//long Startdate=system.currenttimemillis (); for (int i = 0; i < 1000;            i++) {Final int id = i; Executor.submit (New futuretask<integer> (new Pgpagemodelworker (ID)) {@Override Protect                    Ed void done () {try {modelmap.put ("key" + ID, get ());d Ata.add (Get ());                    } catch (Exception e) {modelmap.put ("key" + ID, 0);                    } finally {Countdownlatch.countdown ();            }    }            }); }SYSTEM.OUT.PRINTLN ("----Do other things------"); SYSTEM.OUT.PRINTLN ("------Do other things----"); SYSTEM.OUT.PRINTLN ("-----Do other things-----"); try {thread.sleep (3000); System.out.println ("Sleeps three Seconds");} catch (Interruptedexception e) {e.printstacktrace ();} SYSTEM.OUT.PRINTLN ("-----Do other things-----"); SYSTEM.OUT.PRINTLN ("-----Do other things-----"); SYSTEM.OUT.PRINTLN ("-----Do other things-----");        SYSTEM.OUT.PRINTLN ("-----Do other things-----"); int timeout = 3000; Countdownlatch.await (timeout, timeunit.milliseconds);//Timeout long enddate=system.currenttimemillis ();        System.out.println ("Execution Time:" + (enddate-startdate));iterator<string> Iterator=modelmap.keyset (). Iterator ();            while (Iterator.hasnext ()) {String key=iterator.next ();        System.out.println (key+ "-----" +modelmap.get (key)); }SYSTEM.OUT.PRINTLN ("---list traversal--------"); Long Start1=system.currenttimemillis (); for (Integer D:data) {System.out.println (d);} SYSTEM.OUT.PRINTLN ("Traversal Time:" + (System.currenttimemillis ()-start1)); System.out.println ("List.size:" +dAta.size ()); }}

Countdownlatch

It allows some tasks to continue to run after the following content, each task itself after the completion of the counter minus one, until the counter cleared 0, the following content can continue to run, or will block wait


Countdownlatch has the following basic methods:

1) await (), block wait until the counter is zeroed

2) await (int timeout, timeunit unit), which causes the thread to block unless it is interrupted or exceeds the maximum waiting time

If the counter zeroing is reached, await returns true if the wait exceeds the maximum wait time, which returns false

3) Countdown (), counter minus one, when the counter is cleared, the await thread is awakened, the thread continues execution

4) GetCount (), gets the size of the current counter


public static void Main (string[] args) throws exception{final Countdownlatch cdorder=new countdownlatch (1);    Final Countdownlatch cdanswer=new Countdownlatch (3);    System.out.println ("Waiting for athletes to enter---------------");        try {executorservice executor= executors.newcachedthreadpool ();;            for (int i = 1; i < 4; i++) {final int c=i;                        Executor.submit (New Runnable () {@Override public void run () {try {                        System.out.println ("Athlete" +c+ "ready");                        Cdorder.await ();                        System.out.println ("Athlete" +c+ "has started");                        Random rand = new Random ();                        Thread.Sleep (Rand.nextint (2000) + 500);                        Cdanswer.countdown ();                        System.out.println ("Athlete" +c+ "has reached the end");                    System.out.println ("Still Left" +cdanswer.getcount () + "athlete not arrived");                } catch (Exception e) {        System.out.println ("runable problem i=" +c);                    E.printstacktrace ();        }                }            });        }} catch (Exception e) {System.out.println ("thread Problem");    E.printstacktrace ();        } try {thread.sleep (1000);        System.out.println ("The referee has issued a command-----------------");        Cdorder.countdown ();        Cdanswer.await ();    SYSTEM.OUT.PRINTLN ("Referee announces Results------------");        } catch (Exception e) {System.out.println ("main problem");    E.printstacktrace (); }}


Five, Completionservice

A service that separates the production of new asynchronous tasks from the results of using the completed tasks, which the producer submit to perform. The consumer take the completed tasks and process their results in the order in which they were completed


Completionservice has the following basic methods:

Future<v> Submit (callable<v> Task);

Future<v> Submit (Runnable task, V result);

Future<v> take () throws interruptedexception;

Future<v> poll ();

Future<v> Poll (long timeout, timeunit unit) throws Interruptedexception;


Class completionservice2{public    static void Main (string[] args) {        Executorservice executor = Executors.newcachedthreadpool ();        completionservice<integer> Completionservcie = new executorcompletionservice<integer> (                executor);        Completionservcie.submit (New Runnable () {            @Override public            void Run () {                try {                    thread.sleep (a);                } catch (Interruptedexception e) {                    e.printstacktrace ();                }            }        },1);        try {            System.out.println (Completionservcie.poll (), timeunit.milliseconds). get ());        } catch ( Interruptedexception e) {            e.printstacktrace ();        } catch (Executionexception e) {            e.printstacktrace ();        }    }}








Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Multithreading using learning notes

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.