In-depth understanding of java concurrent programming Basics (a) ------- concurrent programming concepts

I. Introduction

  Long overdue concurrent programming, today will begin the first chapter, it is divided into two most learning: Basics and Advanced chapter is divided into the following began Basics of learning.

Second, concurrent programming concepts

2.1. Synchronization (Sync) and asynchronous (Async)

2.2.1 Synchronization (Sync)

  The so-called synchronization is issued when a function call, until no results, the call will not return or continue to follow up.
  According to this definition, Java methods are all synchronous call, should have to wait until the results will continue. We're talking about synchronous and asynchronous time, generally refers specifically to those tasks that require collaboration or other end will take some time to complete. In simple terms, the synchronization is a must do one thing, such as a front done in order to do the next thing.

2.2.2 asynchronous (Async)

  Asynchronous and synchronous contrast, when an asynchronous procedure call is issued, until the caller was not a result, subsequent operations can proceed. When the call is completed, usually informs the caller through the state, notification and callback. For asynchronous calls, calls not returned by the caller control.

Illustrated as follows:

2.2. Concurrent (Concurrency) and parallel (of Parallelism)

  Concurrency and parallelism are two concepts very easily confused. They can perform together represent two or more tasks, but the focus is different. Concurrent emphasis on alternately performed a plurality of tasks, and the task is still possible between a plurality of serially, in parallel is "both" in the true sense, as shown below:

  In fact, if there is only one CPU in the system, the use of multi-process or multi-threaded task, then the real environment, these tasks can not be true parallel, after all, a CPU can execute only one instruction, multi-process, or in this case multithreading is concurrent, not parallel (operating system will continue to multi-task switching). Parallel only real (such as a multi-core CPU) may occur in the system has a plurality of CPU.

2.3. The critical area

  Represents the critical area of ​​public resources or share data, it can be used by multiple threads. But every time there is a thread can only use it once a critical resource area is occupied, other threads must wait to continue using the resource after resource release. In the Java program development, resources for such operations generally need to do synchronization, for example, the following code, with the synchronized keyword is to synchronize critical sections resources:

package com.MyMineBug.demoRun.test;

/**
 * 
 * @author 18360
 *
 */
public class SyncTest implements Runnable {

	// 临界区资源
	public static SyncTest instance = new SyncTest();

	@Override
	public void run() {
		synchronized (instance) {

		}
	}
	
	public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new SyncTest());
        Thread t2 = new Thread(new SyncTest());
        t1.start();
        t2.start();
        t1.join();
        t2.join();
    }

}

复制代码

2.4 Blocking (Blocking) and non-blocking (Non-Blocking)

  Blocking and non-blocking usually used to describe the interaction between many threads. For example, a thread takes up a shared resource, then all other resources needed in this thread must wait in this critical area. Waiting causes the thread to hang, this situation is blocked. At this point, if the resource-thread has been reluctant to free up resources, then the other thread is blocked in this critical area of ​​the threads are not working.

  Non-blocking means contrary, it stresses that there is a thread can interfere with other threads, all threads will attempt to continue to perform ahead

2.5 Deadlock (Deadlock), hunger (Starvation) and livelock (Livelock)

2.5.1 deadlock (Deadlock)

  Deadlock generally refers to two or more threads hold each other needed resources, and always waiting for the other to release the A blocking state. For example there are two threads A and B while sharing resources critical region C, when occupied by C A, B is blocked, however, release the need to use A resource B, this way, it becomes a A've been waiting for B, B has been waiting for a, between each other forever waiting for the release of the other state.

The following is a simple example of deadlock:

package com.MyMineBug.demoRun.test;

public class Demo1 {

	public static String obj1 = "obj1";
	public static String obj2 = "obj2";

	public static void main(String[] args) {
		Thread a = new Thread(new Lock1());
		Thread b = new Thread(new Lock2());
		a.start();
		b.start();
	}

}

	class Lock1 implements Runnable {
	
		@Override
		public void run() {
			try {
				System.out.println("Lock1 running");
				while (true) {
					synchronized (Demo1.obj1) {
						System.out.println("Lock1 lock obj1");
						Thread.sleep(3000);// 获取obj1后先等一会儿,让Lock2有足够的时间锁住obj2
						synchronized (Demo1.obj2) {
							System.out.println("Lock1 lock obj2");
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
	
		}
	
	}
	
	class Lock2 implements Runnable {
	
		@Override
		public void run() {
			try {
				System.out.println("Lock2 running");
				while (true) {
					synchronized (Demo1.obj2) {
						System.out.println("Lock2 lock obj2");
						Thread.sleep(3000);
						synchronized (Demo1.obj1) {
							System.out.println("Lock2 lock obj1");
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
	
		}
	
	}


复制代码

Results are as follows:

In general, deadlock occurs due to the design of the program caused by an irrational and difficult to resolve the deadlock, the best way is prevention.

2.5.2 hunger (Starvation)

  Hunger refers to one or more threads for various reasons unable to obtain the resources needed, resulting in has been unable to perform. Such as its thread priority is too low, and the high priority thread continues to occupy the resources it needs, resulting in low priority resource not work.

2.5.3 Livelock (Livelock)

  Livelock situation is thread a very interesting situation, in life we ​​may encounter such a situation, and that is to go out when the door might encounter someone you going to let him advanced the door, he was going to let you to go out as a result, both of them back up each other, then you're going to step forward when the other side also to go out, to and fro has been stuck in the door. Of course, this kind of thing normal people will soon be resolved, but if the thread is met not so lucky.

  If two threads are occupied with public resources, and adhering to the principle of "humility" and take the initiative to resources for others to use, you let me, would have resulted in resources between the two threads continue to take all the beating but between threads less than of resources, such a situation is to live locked.

  If you feel good, make a point of praise! ! !

  Share Technology And Love Life

Guess you like

Origin juejin.im/post/5d7dfa04e51d453b5e465bdd