Java reading notes (4)-Multithreading (two)

Source: Internet
Author: User

2016-1- 2

  1. Thread Communication

    • Traditional thread Communication

      • The Object class provides wait (),notify () , and Notifyall three methods

      • Application:synchronized modified synchronous method or synchronized method

      • Wait (): causes the current thread to wait until another thread calls the synchronization Monitor's notify () or notifyall method to wake the thread, calling wait method, this thread releases the lock on the synchronization monitor

      • notify (): wakes up a single thread waiting on this synchronization monitor. If more than one thread is waiting, one is randomly awakened

      • notifyall (): wakes up all the threads waiting on this sync monitor

    • Using Condition to control thread communication

      • For scenarios that use the lock object to synchronize, theCondition instance is bound to a lock object

      • Lock replaces synchronous or synchronous code block,Condition replaces the function of synchronization monitor

      • await (), signal (), Signalall ()

      • Private final Lock lock=new Reentrantlock ();

      • Private final Condition cond=lock.newcondition ();

      • Cond.await ()

      • Cond.signalall ()

    • blockingqueue Control thread communication

      • add (e E), off (e), put (e)

      • remove (), poll (), take ()

      • element (), Peek ()

    • Arrayblockinqueue, Linkedblockingqueue, Priorityblockingqueue, Synchronousqueue, Delayqueue

    • Blockingqueue<stirng> bq=new arrayblockingqueue<> (2);

      Bg.put ("Java")

  2. Thread Groups (Threadgroup) and unhandled exceptions

      • Programs can control threads directly on a group-by-unit

      • Cannot change the owning thread group while the thread is running

      • Threadgroup:activecount (), interrupt (), Isdaemon (), Setdaemon (), setmaxpriority ()

      • A useful method is also defined in threadgroup :void uncaughtexception (thread t,throwable e), which can handle exceptions thrown by any thread within a thread group

      • When catching an exception with catch , the exception is not propagated to the previous caller, but when the exception is handled with the exception handler, the exception is still propagated to the previous caller

  3. Thread pool

    • When you need to create lots of short-lived threads in your program, you should consider using a thread pool. Thread pool creates a large number of idle threads at system startup

    • Thread pool implemented by Java5

      • Returns a Executorservice object that represents a thread pool:newcachedthreadpool () newfixedthreadpool (int nthreads), Newsinglethreadexecutor ()

      • New Scheduledthreadpool (int corepoolsize), new Singlethreadscheduledexecutor ()

      • To use the thread pool to perform the threading task:

        1. Call the static factory method of the executors class to create a Executorservice object that represents a thread pool;

        2. Create an instance of the Runnable implementation class or callable implementation class to perform the task as a thread;

        3. Invoke the submit () method of the Executorservice object to submit the Runnable instance or callable instance;

        4. The task finishes and finally closes the thread pool shutdown ().

    • Java7 The new forkjoinpool

      • Take advantage of the performance benefits of multi- CPU, multi-core CPUs

      • Split a task into multiple "small tasks" parallel computations and combine the results of multiple small tasks into a total calculation result

      • Forkjoinpool is an implementation class of Executorservice , so it is a special thread pool

      • Created aForkjoinpoolinstance, you can call theForkjoinpoolOfSubmit (forkjointask Task)OrInvoke (forkjointask Task)method to perform the specified task. whichForkjointaskRepresents a task that can be merged in parallel.Forkjointaskis an abstract class, and it has two abstract subclasses: RecursiveactionAndRecursivetask。 whichRecursivetaskRepresents a task with a return value, while therecursiveactionRepresents a task that has no return value.

  4. Thread-related classes

    • ThreadLocal Class

      • Represents a thread-local variable that allows each thread to create a copy of the variable by putting the data in ThreadLocal

      • When writing multithreaded code, you can encapsulate an insecure whole variable into ThreadLocal, or use ThreadLocal to save the object's thread-related state.

      • The problem areas that the ThreadLocal class and thread synchronization mechanisms face are different

      • Use the synchronization mechanism if you need to share resources between multiple resources to implement thread communication, or if you are only isolating conflicts between multiple threads, use ThreadLocal

    • Wrapped Thread Unsafe collection

      • You can use the static methods provided by collections to wrap these collections into thread-safe collections.

        1. <T> collection<t> synchronizedcollections (collection<t> c): returns the specified Collection The corresponding thread-safe collection;

        2. Static <T> list<t> synchronizedlist (list<t> List)

        3. Static <K,V> map<k,v> Synchronizedmap (map<k,v> m)

        4. Static <T> set<t> Synchronizedset (set<t> s)

        5. Static <K,V> sortedmap<k,v> Synchronizedsortedmap (sortedmap<k,v> m)

        6. Static <T> sortedset<t> Synchronizedsortedset (sortedset<t> s)

      • If you need to wrap a collection as a thread-safe collection, you should wrap it immediately after creation

        HashMap M=collections.synchronizedmap (New HashMap ());

    • Thread-Safe Collection classes

      • java.util.concurrent Bag

      • A collection interface and implementation class that supports efficient concurrent access

        1. Collection class starting with Concurrent : A collection that supports concurrent access

        2. Collection class starting with Copyonwrite : For scenarios where read operations are much larger than write operations, such as caching

Java reading notes (4)-Multithreading (two)

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.