Java concurrency basics and java concurrency Basics

Source: Internet
Author: User

Java concurrency basics and java concurrency Basics

Concurrency is the ability to run multiple programs in parallel or run multiple parts of a program in parallel. If a time-consuming task in a program can be run asynchronously or in parallel, the throughput and interactivity of the entire program will be greatly improved. Modern PCs have multiple CPUs or one CPU has multiple cores. Whether multi-core capabilities can be used properly becomes the key to a large-scale application.

Basic thread usage

There are two methods to compile the code executed during Thread running: one is to create an instance of the Thread subclass and override the run method, and the other is to implement the Runnable interface when creating the class. Of courseCallableThis is also a method. The combined implementation of Callable and Future can obtain the returned value after the task is executed, while the Runnable and Thread methods cannot obtain the results after the task is executed.

Public class ThreadMain {public static void main (String [] args) {MyThread myThread = new MyThread (); new Thread (myThread ). start (); new MyThreas2 (). start () ;}// method 1, implementing the Runable Interface class MyThread implements Runnable {@ Override public void run () {System. out. println ("MyThread run... ") ;}// Method 2: Inherit the Thread class, Override the run () method class MyThreas2 extends Thread {@ Override public void run () {System. out. println ("MyThread2 run... ");}}

Once the thread starts, the start () method will return immediately, instead of waiting for the run () method to return after execution, as if the run method is executed on another cpu.

Note: The common error in creating and running a thread is to call the run () method of the thread rather than the start () method, as shown below:

Thread newThread = new Thread(MyRunnable());newThread.run();  //should be start();

At first, you don't feel anything wrong, because the run () method is indeed called as you wish. However, in fact, the run () method is not executed by the newly created thread, but by the current thread. That is, it is executed by the thread that executes the above two lines of code. To run the run () method on a new thread, you must call the start method of the new thread.

Callable and Future are combined to obtain the return value after the task is executed.:

public static void main(String[] args) {    ExecutorService exec = Executors.newSingleThreadExecutor();    Future<String> future = exec.submit(new CallTask());    System.out.println(future.get());}class CallTask implements Callable {    public String call() {        return "hello";    }}

Set the thread name for the thread:

MyTask myTask = new MyTask();Thread thread = new Thread(myTask, "myTask thread");thread.start();System.out.println(thread.getName());

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

 

Volatile

Synchronized and Volatile play an important role in multi-thread concurrent programming. Volatile isLightweightSynchronizedIt ensures the "visibility" of shared variables in multi-processor development ". Visibility means that when a thread modifies a shared variable, another thread can read the modified value. In some cases, it has lower overhead than synchronized, but volatile cannot guarantee the atomicity of variables.

When the volatile variable is used for write operations (there is a lock command in the assembly), the lock command has two functions in the multi-core system:

  • Write the current CPU cache row back to the system memory.
  • This write-back operation will cause data with the changed address cached by other CPUs to become invalid.

The cache consistency principle is followed for multiple CPUs. Each CPU uses sniffing data transmitted on the bus to check whether its cache value has expired. When it finds that the memory address corresponding to the cache is modified, set the corresponding cache row to invalid. The next data operation will be re-read from the system memory. For more volatile knowledge, click to deeply analyze the implementation principle of Volatile.

 

Synchronized

Synchronized has always been a veteran role in multi-thread concurrent programming. Many people call it a heavyweight lock. However, after Java SE1.6 optimizes Synchronized, in some cases, it is not that heavy.

Every object in Java can be used as a lock. When a thread tries to access the synchronous code block, it must first get the lock and release the lock when exiting or throwing an exception.

  • For the synchronization method, the lock is the current instance object.
  • For static synchronization methods, the lock is the Class Object of the current object.
  • For synchronous method blocks, the lock is the object configured in the Synchonized brackets.

The synchronized keyword cannot be inherited. That is to say, the synchronized Method in the base class is not synchronized by default in the subclass. When a thread tries to access the synchronous code block, it must first obtain the lock, exit or throw an exception, and release the lock. Every object in Java can be used as a lock. What is the lock? The lock exists in the Java object header. if the object is of the array type, the virtual machine uses three word (word width) to store the object header. if the object is of the non-array type, the object header is stored with 2 Characters in width. For more synchronized knowledge, click Synchronized in Java SE1.6.

 

Thread Pool

The thread pool is used to manage worker threads, including a queue of tasks waiting for execution. The task queue in the thread pool is a Runnable set. The worker thread is responsible for extracting and executing Runnable objects from the task queue.

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

Java provides four thread pools through Executors:

  • NewCachedThreadPool: Creates a cache thread pool. If no idle thread exists for a new task, a new thread is created. If the idle thread exceeds a certain period of time, it is recycled.
  • NewFixedThreadPool: Creates a fixed number of thread pools.
  • NewSingleThreadExecutor: creates a single-threaded thread pool that uses only one thread to execute tasks, ensuring that all tasks are executed in FIFO order.
  • NewScheduledThreadPool: Creates a fixed-length thread pool that supports scheduled and periodic task execution.

The underlying layers of these thread pools call ThreadPoolExecutor to create a thread pool.

ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)
  • CorePoolSize (basic thread pool size): when a task is submitted to the thread pool, the thread pool creates a thread to execute the task, even if other idle basic threads can execute new tasks, they will create threads. When the number of tasks to be executed exceeds the basic size of the thread pool, they will not be created. If the thread pool's prestartAllCoreThreads method is called, the thread pool will create and start all basic threads in advance.
  • MaximumPoolSize (maximum thread pool size): Maximum number of threads allowed to be created in the thread pool. If the queue is full and the number of created threads is smaller than the maximum number of threads, a new thread execution task is created in the thread pool. It is worth noting that the parameter of unbounded task queue is ineffective.
  • KeepAliveTime (thread activity Holding Time): The time for keeping the worker threads in the thread pool alive after idle. Therefore, if there are many tasks and each task is executed for a short time, you can increase the time to improve the thread utilization.
  • TimeUnit (unit of thread activity holding time): Optional Unit: one day (DAYS), hour (HOURS), minute (MINUTES), Millisecond (MILLISECONDS), microsecond (MICROSECONDS, 1‰ MILLISECONDS) and S (NANOSECONDS, 1‰ microseconds )., You can select the following types of blocking Queues:
  • WorkQueue: a blocking queue used to save tasks waiting for execution.

 

    • ArrayBlockingQueue: A Bounded blocking Queue Based on an array structure. This queue sorts elements according to the FIFO (first-in-first-out) principle.
    • LinkedBlockingQueue: a blocking Queue Based on the linked list structure. This queue is sorted by FIFO (first-in-first-out) elements, and the throughput is usually higher than that of 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 call the remove operation. Otherwise, the insert operation is always in the blocking state, and the throughput is usually higher than the provisioned blockingqueue. The static factory method Executors. newCachedThreadPool uses this queue.
    • PriorityBlockingQueue: An infinite blocking queue with a priority.

When a new task is submitted to the thread pool, the process is as follows:

 

Refer:

1. In-depth Analysis of Volatile implementation principles

2. Synchronized in Java SE1.6

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.