Sister school to teach Java: unruly multithreading

00 origin, story

"How kind of repercussions effect ah?" "Brother, on a" set of Sanmei very concerned about her proposed "sister school to teach Java" column.

"The article views than the first chapter," generic "much better."

"This is good news ah, indicating more people to accept the creation of a brother." Sanmei elated up.

"Perhaps no comparative."

"There is no contrast? I look a bit brother seven months ago to write the article, the water is really ah, hee hee." Sanmei sell a Moe, continued, "To be honest, but there are still readers willing to read , it is really incredible. "

"Do you want a beating you?"

"Do not ah. I mean, brother and now readers really lucky, because they see the higher quality of the article." Sanmei continue with impunity spoke her truth.

"Yes ah, much better than before, but I would also like more effort, this time the theme is" multi-threaded "Sanmei you ready?"

"As early as ready. Let me continue to question it, brother you continue to answer." Sanmei already eager.

01, brother, what is the thread ah?

Sanmei, brother to hear you speak slowly ah.

To understand the thread, you must first understand the process, because the thread is a unit process. You see, I have this computer at the same time opened a lot of processes, such as typing with this input method, wrote the role of the browser, listen to songs with this music player.

These processes may be doing several things at the same time, such as the music player, while the lyrics scroll while playing audio. That is to say, within a process that may simultaneously running multiple threads (Thread), each thread is responsible for different tasks.

Since each process at least do one thing, so that a process has at least one thread. In the Java program which, at least there will be a main method, which is called the main thread.

Can execute multiple threads simultaneously, implementation and multiple processes are the same, are determined by the operating system. The operating system can quickly switch between multiple threads, each thread runs alternately. The shorter the switching time, the higher the efficiency of the program.

The relationship between processes and threads can use a simple words, is "the process is the father and mother, pipe thread with many of the children."

02, brother, why use multithreading ah?

Third sister, brother to go to a cup of coffee, come listen brother tell you slowly.

As a multi-threaded multi-task, complicated by the way, a lot of advantages.

First, reduce the response time of the application.

For computers, IO read and write and network communication is relatively time-consuming task, if you do not use multiple threads, then the other less time-consuming task must also wait to perform these tasks after the end.

Second, take full advantage of multi-core CPU.

The operating system may ensure that when the number of threads is not larger than the number of CPU, running on different threads on different CPU. However, even if the number of threads exceeds the number of CPU, operating system and thread pool will do the maximum possible to reduce the time it takes to switch a thread, the maximum possible advantage of concurrency, improve program performance.

Third, compared to multi-process, multi-thread is a more "efficient" multi-tasking mode.

For different processes, they have separate data space, the data must be shared between the "communications" mode. And you do not need threads, shared data space between threads in the same process.

Of course, if two threads access the same object, and each thread calls a method to modify the object's state, it will bring new problems.

What's the problem? Let's be illustrated by the following examples.

public class Cmower {

    public static int count = 0;

    public static int getCount() {
        return count;
    }

    public static void addCount() {
        count++;
    }

    public static void main(String[] args) {
        ExecutorService executorService = new ThreadPoolExecutor(10, 1000, 60L, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(10));

        for (int i = 0; i < 1000; i++) {
            Runnable r = new Runnable() {

                @Override
                public void run() {
                    Cmower.addCount();
                }
            };
            executorService.execute(r);
        }
        executorService.shutdown();
        System.out.println(Cmower.count);
    }

}

We create a thread pool, thread pool allows for loop through the implementation of 1000 threads, each call to a Cmower.addCount()method of operation count value plus 1, 1000 when the thread is finished, the print count value of the console.

As a result, what would it be?

998、997、998、996、996

But hardly what we want answers 1000.

03, brother, why the answer is not 1000 yet?

Sanmei ah, too strong a bubble of coffee. However, the benefits are more concentrated a little pick-me-up.

In the program operation, the data will need to copy calculation from physical memory to a CPU cache which, after the calculation, then the data cache to physical memory refresh them.

Take count++it. When a thread executes this statement will start reading the values of the count of physical memory, then copy them to the cache, CPU instruction execution count are incremented, then the cache count value of the latest refresh to the physical memory of them.

In the multi-core CPU, each thread might run on a different CPU, so each thread in a high-speed running will be dedicated cache. A thread count being assumed are incremented, this time value in the cache thread B count is still 0, the count operation after adding a value of 1. The last two threads to refresh the latest value of 1 to physical memory, instead of the ideal 2.

This variable is accessed by multiple threads is called shared variables, they often need to be protected.

04, brother, then how to protect shared variables?

Sanmei ah, so I Hekou coffee lift their spirits.

For example, the count appears, may be modified in the following manner.

public static AtomicInteger count = new AtomicInteger();

public static int getCount() {
    return count.get();
}

public static void addCount() {
    count.incrementAndGet();
}

Supports atomic operation (i.e., operation or a plurality of or all operations performed, and the process will not be interrupted execution of any factor, or to not executed) AtomicIntegerinstead of the basic type int.

Simple analysis AtomicIntegerclass, the source code can be seen in an interesting variable unsafe.

private static final Unsafe unsafe = Unsafe.getUnsafe();

UnsafeIt is that one can perform insecure, fallible special class operation. AtomicIntegerUsing the Unsafeatomic operation method compareAndSwapInt()to update the data, also known as CAS.

public final native boolean compareAndSwapInt(Object o, long offset,
                                                int expected,
                                                int x);

O parameter to the CAS operation is performed (for example COUNT) parameter offset is a memory location, expected parameter is a desired value, the parameter x is required to update the value.

The general synchronization method will read from the address offset value A, to perform some new value obtained by calculation after the B, then the value of offset CAS from A to B. If the value of the offset has not been changed at the same time, the CAS operation was successful.

CAS allowed to perform "read - modify - write" operation, without having to worry about other threads to modify the variable, because if another thread to modify variables, CAS will detect it (and failed), the algorithm can recalculate the operation.

AtomicIntegerSource class is worth noting that there is a variable value.

private volatile int value;

valueUse keywords volatileto ensure visibility - when multiple threads access the same variable, a thread changes the value of this variable, other threads can immediately see the modified values.

When a shared variable is volatilelater modified, it is modified values will be updated immediately into physical memory, when there are other threads need to read, go read the new physical memory value.

Without being volatilemodified shared variables can not guarantee the visibility, because of the uncertainty of these variables will be written to the physical memory at what time, when the other threads to read, read the original may still be the old value.

Of particular note is that volatilethe keyword variable visibility only guarantee and can not guarantee atomic.

05, the story to be continued

"Brother," multi-threaded "on it first talked about this, I can not more absorbed!" Sanmei attitude is very sincere.

"can."

"Brother, I remember the last time you said to give large contributions, how about the result?" Sanmei asked with concern.

"Oh, I am embarrassed to say, only harvested two thumbs up emoticon, or may be based on compassion. I can not be scared submission, first adhere to write it!"

"Bleak ending so you really do not have a number to reprint it? I think that there are over three hundred public contribution group number yet." Sanmei very sad.

"" Sister school to teach Java "series title might be a little party, right?"

"Brother, since the decision to write, do not doubt yourself. Sanmei least liked this style ah." After listening to Sanmei earnestness, I kind of heart and self-doubt vanished.

 

Guess you like

Origin www.cnblogs.com/qing-gee/p/10982933.html