Java Concurrency Basics Summary

Source: Internet
Author: User
Tags sorts visibility

Concurrency is the ability to run multiple programs in parallel or to run multiple parts of a program in Parallel. If a time-consuming task in the program can run asynchronously or in parallel, the throughput and interactivity of the entire program will be greatly improved. Modern PCs have multiple CPUs or multiple cores in one cpu, and the ability to properly use multicore will be key to a large-scale application.

Thread Basic usage

There are two ways to write code that executes when the thread runs: one is to create an instance of the thread subclass and override the run method, and the second is to implement the Runnable interface when creating the class. of course, implementing callable is also a way of combining callable and future implementations to get the return value after the task is completed, and the runnable and thread methods cannot get the result after the task is Executed.

 public classThreadMain { public Static voidmain (string[] Args) {MyThread MyThread=NewMyThread (); NewThread (myThread). Start (); NewMyThreas2 (). Start (); }}//the first way to implement the Runable interfaceclassMyThreadImplementsRunnable {@Override public voidrun () {System.out.println ("MyThread Run ..."); }}//the second way, inheriting the thread class, overriding the run () methodclassMyThreas2extendsThread {@Override public voidrun () {System.out.println ("MyThread2 Run ..."); }}

Once the thread is started, the start () method returns immediately without waiting for the run () method to return after execution, as if the Run method was executed on a different cpu.

Note: A common mistake that is made to create and run a thread is to call the Thread's run () method instead of the start () method, as Follows:

New Thread (myrunnable ()); newthread.run ();   // should be start ();

At first you don't feel anything wrong, because the run () method is actually called as you Wish. however, in fact, the run () method is not executed by the new thread that was just created, but by the current Thread. That is, executed by the thread executing the above two lines of Code. To have the new thread created execute the run () method, you must call the new Thread's start Method.

the callable and the future combine to achieve the return value after performing a task :

 public Static void main (string[] Args) {    = executors.newsinglethreadexecutor ();    Future <String> future = Exec.submit (new  calltask ());    System.out.println (future.get ());} class Implements callable {    public  String call () {        return ' Hello ';    }} 

To set the thread name for a thread:

Newnew Thread (mytask, "mytask thread"); thread.start (); System.out.println (thread.getname ());

When creating a thread, you can give the thread a Name. It helps us to differentiate between different threads.

Volatile

Synchronized and volatile play an important role in multithreaded concurrent programming, and volatile is a lightweight synchronizedthat guarantees the "visibility" of shared variables in multiprocessor Development. Visibility means that when a thread modifies a shared variable, another thread can read the modified Value. It is less expensive than synchronized in some cases, but volatile does not guarantee the atomicity of the Variable.

When a volatile variable is written (with a lock instruction under assembly), the lock directive has 2 functions under a multicore system:

    • Writes the current CPU cache line back to system Memory.
    • This writeback operation causes the other CPU to cache the data that has changed the ADDRESS.

Multi-cpu follows the principle of cache consistency, each CPU by sniffing the data propagated on the bus to check whether its cache value expired, when the memory corresponding to the cache address is modified, the corresponding cache row is set to an invalid state, the next time the data operation will be re-read from the system memory. For more information on volatile, please click here to drill down to the principle of volatile.

Synchronized

In multi-threaded concurrent programming, synchronized has always been a veteran, and many people will call it a heavyweight lock, but with the various optimizations that Java SE1.6 has made to synchronized, in some cases it's not that heavy.

Every object in Java can be a lock, and when a thread tries to access a synchronous block of code, it must first get a lock, exit or throw an exception when it must release the LOCK.

    • For synchronous methods, The lock is the current instance Object.
    • For a static synchronization method, the lock is the class object of the current Object.
    • For synchronous method blocks, The lock is an object configured in Synchonized Brackets.

The Synchronized keyword cannot be inherited, meaning that the synchronized method in the base class is not synchronized by default in Subclasses. When a thread attempts to access a synchronization code block, it must first obtain a lock, exit or throw an exception when the lock is Released. Every object in Java can be used as a lock, so where does the lock exist? The lock exists in the Java object header, and if the object is an array type, the virtual machine stores the object header with 3 word widths, or 2 characters wide if the object is a Non-array type. For more synchronized knowledge, Click Synchronized in Java SE1.6.

Thread pool

The thread pool is responsible for managing worker threads and includes a queue of tasks waiting to be executed. The Thread Pool's task queue is a runnable collection that the worker thread takes to fetch and execute the Runnable object from the task Queue.

Executorservice Executor  = Executors.newcachedthreadpool ();  for (int i = 0; i < 5; i++) {    executor.execute (new  MyThread2 ());} Executor.shutdown ();

Java provides 4 kinds of thread pools through executors:

    • Newcachedthreadpool: creates a cacheable thread pool that, If no idle thread is created for a new task, creates a new one, which is recycled if the idle thread exceeds a certain amount of time.
    • Newfixedthreadpool: creates a thread pool of a fixed number of THREADS.
    • Newsinglethreadexecutor: creates a single threaded thread pool that uses only one thread to perform tasks, ensuring that all tasks are executed in FIFO order.
    • Newscheduledthreadpool: Create a fixed-length pool that supports timed and recurring task Execution.

The bottom of the thread pool above is called Threadpoolexecutor to create the thread Pool.

Threadpoolexecutor (intintlong keepalivetime, timeunit unit, blockingqueue<runnable > WorkQueue)
    • Corepoolsize (basic size of the thread pool): when a task is submitted to the thread pool, the line pool creates a thread to perform the task, and the thread is created even if other idle basic threads are able to perform new tasks, and is no longer created until the number of tasks that need to be executed is larger than the thread pool base Size. If the thread Pool's Prestartallcorethreads method is called, the thread pool creates and starts all basic threads in Advance.
    • Maximumpoolsize (maximum thread pool size): The maximum number of threads allowed to be created by a thread Pool. If the queue is full and the number of threads that have been created is less than the maximum number of threads, the thread pool will then create new threads to perform the Task. It is worth noting that if you use the unbounded task queue This parameter has little Effect.
    • KeepAliveTime (thread activity hold time): when the worker thread of the thread pool is idle, the time to remain Alive. So if the task is a lot, and each task executes a short time, you can adjust the time to increase the utilization of the THREAD.
    • Timeunit (unit of thread activity hold time): optional units have day (days), hours (HOURS), minutes (MINUTES), milliseconds (MILLISECONDS), microseconds (microseconds, 1 per thousand milliseconds), and nanoseconds ( nanoseconds, 1 per thousand microseconds). , there are several blocking queues that you can choose From:
    • WorkQueue (task queue): A blocking queue that is used to hold tasks waiting to be executed.

      • Arrayblockingqueue: is a bounded blocking queue based on the array structure, which sorts the elements in FIFO (first-out) Principle.
      • Linkedblockingqueue: A blocking queue based on a linked list structure, which sorts elements in FIFO (first-out), with throughput typically higher than arrayblockingqueue. The static factory method Executors.newfixedthreadpool () uses this Queue.
      • Synchronousqueue: A blocking queue that does not store Elements. Each insert operation must wait for another thread to invoke the Remove operation, or the insert operation will always be in a blocked state, with throughput typically higher than linkedblockingqueue, and the static factory method Executors.newcachedthreadpool Use this Queue.
      • Priorityblockingqueue: an infinite blocking queue with Priority.

When a new task is submitted to the thread pool, its processing flow is as Follows:

    1. First determine if the base thread pool is full? It's not Full. Create a worker thread to perform the task, and go to the next process when it's Full.
    2. second, determine if the work queue is full? Not full then submit a new task to the work queue, full then into the next process.
    3. Finally determine if the entire thread pool is full? It's not Full. Create a new worker thread to perform the task, and fill it with the saturation policy to handle the Task.

Reference:

1, in-depth analysis of the implementation of volatile principle

2, Java SE1.6 in the synchronized

Java Concurrency Basics Summary

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.