[] Concurrent programming concurrent programming you need to know basic concepts

Multi-threaded Java programming is a very important element, which involves a lot of concepts. These concepts we usually always say it, but really let you introduce these concepts, you could really say for sure. This blog will summarize the concept of programming often used in multi-threaded, to understand these concepts can help us better understand multi-threaded programming.

Process (Process) and the thread (Thread)

Processes and threads are the most frequently mentioned concept. In linux, the biggest difference is whether the threads and processes share the same address space, and share the same set of threads that address space will appear the same PID number. Here under the concept of both:

  • The process is the smallest unit of allocation of system resources, can be simply interpreted as a program running on the system is a process.
  • The thread is the smallest unit of CPU scheduling, execution process is a process.
  • A process that contains at least one thread, can contain multiple threads that share the resources of the process. At the same time each thread has a separate runtime stack and program counter, the thread switching overhead is small.
  • It refers to a multi-process operating system to run multiple programs, such as the current operating system running QQ, IE, and other programs at the same micro-channel.
  • Multithreading refers to the same process multiple threads to run simultaneously, such as Thunder running, you can open multiple threads simultaneously download multiple files.

Speaking threads and processes, and is bound to involve the concept of threads number and process number. Here are the ID of each concept.

  • pid: process ID.
  • tgid: thread group ID, group leader of the thread is the process ID, equal to pid.
  • lwp: thread ID. Command used in the user state (such as ps) display mode.
  • tid: thread ID, equal lwp. tid more commonly used in interface functions provided by the system, such syscall (SYS_gettid) and syscall (__ NR_gettid).

Parallel (Parallel), concurrent (Concurrent)

  • Concurrency : refers to multiple threads execute tasks quickly rotate on the same CPU, due to the very fast switching speed, gives the impression that these threaded tasks are carried out at the same time, but in fact only concurrent simultaneously on a logical ;
  • Parallel : refers to the task multiple threads simultaneously on different CPU, is performed simultaneously in the true sense.

Here affix a diagram to explain these two concepts:

Coffee figure above can be seen as CPU, the above is only a coffee machine, equivalent to only one CPU. People drink coffee the only other person in front of finished making coffee to make your own development, that is, at the same time only one person in the production of coffee, which is a concurrent mode. The following figure, there are two coffee machines, there are two corresponding to the CPU, the same time there may be two people to make coffee, a parallel mode.

We find parallel programming, a very important feature is the system with multi-core CPU. If the system is a single-core, not to mention what a parallel programming.

Thread Safety

This concept is probably the most mentioned concept in a multi-threaded programming. During the interview process, I tried to ask the interviewer a few, but almost no one can explain well the concept.

About this concept, I think a lot of people have a misunderstanding, myself included beginning is the case. I began to think that talking about the security thread is a shared variable thread-safe, in fact, we are talking about thread safety means that a piece of code or a method is thread safe. Thread-safe precise definition should look like this:

If the random thread scheduling order does not affect the final results of the implementation of a piece of code, then we think this code is thread-safe .

In order to ensure thread-safe code, Java introduced in a number of useful tools or keywords, such as volatile, synchronized, ThreadLocal, lock, concurrent collections, and CAS thread pool mechanism. These tools are not able to meet the needs of our multi-threaded programming in each scene, not at each scene has a very high efficiency, we need programmers to choose the most suitable technology depending on the scene, perhaps is the existence of our programmers value. (I always think that if there is a good technology can solve the problem in most scenes, then this field must be automated machine can be made. So this area is less need for the number of people involved.)

Deadlock

1 takes up the thread lock A, waiting for the lock B, Thread 2 occupied lock B, waiting for the lock A, in this case causing a deadlock. In a deadlock situation, the relevant code will no longer provide services.

private void deadLock() {
      Thread t1 = new Thread(new Runnable() {
        @Override
        public void run() {
            synchronized (lock1) {
              try {
                Thread.currentThread().sleep(2000);
              } catch (InterruptedException e) {
                e.printStackTrace();
              }
              synchronized (lock2) {
                System.out.println("1");
              }
            }
        }
      });
      Thread t2 = new Thread(new Runnable() {
        @Override
        public void run() {
            synchronized (lock2) {
              synchronized (lock1) {
                System.out.println("2");
              }
            }
        }
      });
      t1.start();
      t2.start();
    }

This code only demonstrates deadlock scenario, in reality you probably will not write code. However, in some more complex scenarios, you may encounter problems, such as to get the lock after t1, because some anomalies do not release the lock (infinite loop). Or is t1 to get a database lock, the lock is released when an exception is thrown, not released.

If you suspect that your code has appeared thread deadlocks, you can dump the thread, and then view the thread state there Blocked thread (java.lang.Thread.State: BLOCKED)


"Thread-2" prio=5 tid=7fc0458d1000 nid=0x116c1c000 waiting for monitor entry [116c1b000] 
    java.lang.Thread.State: BLOCKED (on object monitor) 
     at com.ifeve.book.forkjoin.DeadLockDemo$2.run(DeadLockDemo.java:42) 
     - waiting to lock <7fb2f3ec0> (a java.lang.String) 
     - locked <7fb2f3ef8> (a java.lang.String) 
     at java.lang.Thread.run(Thread.java:695)
     
     
"Thread-1" prio=5 tid=7fc0430f6800 nid=0x116b19000 waiting for monitor entry [116b18000] 
    java.lang.Thread.State: BLOCKED (on object monitor) 
     at com.ifeve.book.forkjoin.DeadLockDemo$1.run(DeadLockDemo.java:31) 
     - waiting to lock <7fb2f3ef8> (a java.lang.String) 
     - locked <7fb2f3ec0> (a java.lang.String) 
     at java.lang.Thread.run(Thread.java:695)

Several ways to avoid deadlock:

  • Try not to take more than one thread simultaneously locks;
  • Avoid a thread simultaneously occupy multiple resources in the lock, try to ensure that each lock only takes a resource.
  • Try using time lock, using lock.tryLock (timeout) instead of using the internal locking mechanism.
  • For database locks, locking and unlocking must be a database connection, otherwise the situation will appear unsuccessful.

hunger

Hunger refers to one or more threads for various reasons unable to obtain needed resources, has been unable to lead the implementation. Such as its thread priority level may be too low, and the high priority thread continues to seize the resources it needs, resulting in a low-priority thread does not work.

In nature, it is easy to happen when the mother bird feeding chicks: As many chicks, limited food, food competition between chicks can be very powerful, often less than nestlings grab the food is likely to be hungry dead. Thread starvation is very similar to this case.

In addition, one thread has been occupied and hold the key resources, leading to other resources need this thread not working properly, one such case is hunger. Compared with the deadlock, hunger is still possible to resolve in the next period of time (for example, high-priority thread has completed the task, no longer perform crazy).

Livelock

Livelock is a very interesting situation. I do not know whether you encountered such a scenario, when you want to take the elevator downstairs to the elevator door opened, then you are ready to go out. But very unfortunately, a person outside the door blocking your way, he wants to come. So, you go left politely, avoid each other. Meanwhile, the other side is also very politely right away, hoping to avoid you. As a result, the two of you on another hit. Ever since, you are aware of the problem, hoping to avoid each other as soon as possible, you immediately go to the right, while he was gone immediately to the left. As a result, it hits! But between human intelligence, I believe that this action was repeated two or three times, you should be able to successfully solve this problem. Because this time, it will instinctively on the TV, to communicate, to ensure that this situation does not recur.

But if this happens between two threads may not be so lucky. If the thread of intelligence is not enough, and are adhering to the principle of "humility", the initiative will free up resources for others to use, it will lead to resource constantly beating between the two threads, one thread can not get all the resources normally performed simultaneously . This situation is livelock.

Synchronous (Synchronous) and asynchronous (Asynchronous)

Synchronous and asynchronous discussion here refers to a method for synchronous and asynchronous methods.

Synchronization method means that after calling this method, the caller must wait until after the completion of the implementation of this method in order to continue down the implementation.
After calling the asynchronous method refers to this method will immediately return calls down immediately in order to continue. Asynchronous method is called is actually carried out by another thread of execution, if the asynchronous method return values can have something to inform the caller in some way notification.

Asynchronous method of ways:

  • Callback mode: a method is called immediately after the return, the result returned to the caller calls a callback function;
  • MQ (publish / subscribe): requester sends a request to MQ, MQ request processing party listens to deal with these requests, and also a return to the MQ, the caller listens to this Queue acquisition processing result of the request processing results;
  • Multi-threaded processing mode: create another thread processing system call requests, such as this method is a method in Spring @Async annotation label.

Critical section

It involves reading and writing shared resources snippet called "critical area."

The following code example, at 1 and 2 is at a critical section of code.

private static class BankAccount{
        String accountName;
        double balance;

        public BankAccount(String accountName,double balance){
            this.accountName = accountName;
            this.balance = balance;
        }

        public synchronized   double deposit(double amount){
            balance = balance + amount; //1
            return balance;
        }

        public synchronized  double  withdraw(double amount){
            balance = balance - amount; //2
            return balance;
        }

    }

Multi-threaded programming strengths and challenges

The purpose is to make concurrent programming faster (to a greater extent the use of CPU resources so that programs run faster) running, but the process of conducting concurrent programming will encounter some challenges.

PS: multi-threaded programming allows us to maximize the use of CPU resources system so as to achieve the purpose of the program run faster (not all cases are multi-threaded faster). But a coin has two sides, the introduction of multi-threaded programming will bring us other problems, such as thread context switching problem, shared variables thread-safety issues, communication problems between threads, thread deadlock issues and multi-threaded hardware resources and other issues affecting. In fact, research in multi-threaded programming is the paradox of this study, but also how to avoid the multi-threaded hole to bring the enjoyment of multi-threaded programming has brought us convenience at the same time. The JDK has provided us with a lot of multi-threading related classes

reference

  • http://blog.chinaunix.net/uid-31404751-id-5753869.html
  • https://blog.csdn.net/hanchao5272/article/details/79513153
  • "High real Java concurrent programming."

Guess you like

Origin www.cnblogs.com/54chensongxia/p/11935433.html