Thread Synchronization

First, the basic concept of the thread synchronization

1. Thread synchronization refers to the coordination and control among multiple threads to access shared resources in each other.

2. Thread synchronization aim is to achieve an orderly controlled multi-threaded access to shared resources, shared resources to protect data security, to avoid deadlock so that the whole system to normal operation.

3. Way to achieve thread synchronization and collaboration are mutually exclusive.

** Note: parallel programming, the more sharing of resources, program design will be more complex, it should reduce the use of shared resources as much as possible.

Second, the thread mutually exclusive synchronization

1. When there are multiple concurrent threads of execution, due to the occupation and give up the threads on the CPU can not predict microscopic, so for shared data insert, delete, update and other operations, failure to take certain measures, the acquired data is likely to be incorrect .

2. To prevent this from happening, Java provides a synchronization mechanism way that is mutually exclusive, that is, with the synchronized keyword lock way to achieve.

3. Mutual exclusion refers to critical resources while allowing only one thread to access it, it is unique and exclusive, ensuring atomicity thread on the critical resource access.

4. Acting synchronized keyword is: to ensure that only a particular block of code execution thread at the same time, i.e., the atomicity code block.

5. There are three ways to use the synchronized:

① sync block.

② synchronized instance methods.

③ synchronization class method (static method).

6. Sync block

① surrounded by a synchronized block of code called a synchronization code blocks;

②synchronized code block needs to receive a parameter, which is an object, the lock object may be called a code block (also called synchronization lock);

③ When any thread holds the lock object before the block of code lock locked object;

④ If a thread holds the lock, once the object, while another thread that is not held by the lock object, in order to achieve a particular thread-based mutex lock of the object.

** Note: The thread holds the lock object does not affect the accounting methods and properties of other threads to access the object's lock. A plurality of threads on a competitive scramble monitor lock object, the thread has finished the execution code block, i.e. release the lock of the monitor.

7. Examples synchronization method

①public synchronized void show () {// function code}.

② with the keyword is in front of the synchronized method, i.e., to achieve a synchronization, equivalent to the entire method is a method of block synchronization code, which is the object lock this.

8. Synchronous static method

①写法:public synchronized static void fun(){//…}。

② is in front of the synchronized static method with the keyword, the overall process is also seen as a sync block, which lock object more specific, where the class corresponds to the lock object.

Third, the deadlock

1. When the thread loop is dependent on two pair of synchronized target a deadlock occurs.

2. For example: a thread enters the monitor object obj1, the object obj2 and waiting on a monitor; while the other thread enters the monitor object obj2, and waits for the object obj1 on a monitor, i.e., a deadlock occurs.

3. Deadlock rarely happens, but in the event it is difficult to debug.

Fourth, cooperation threads

1. Collaboration is a multi-threaded thread synchronization on the basis of mutual exclusion, between the threads in accordance with certain conditions, have a purpose and a plan to work together to interact, which is a more advanced way to thread synchronization.

2. Java provides a well-designed inter-thread communication mechanism that is wait-notify mechanism, the thread can be achieved through the coordination mechanism.

3. wait-notify mechanism by using three methods wait (), notify () and notifyAll () to achieve.

4. These three methods are defined in the Object class, a modified example method is final.

5. These three methods must be called in synchronized code, and only lock the object before calling these three methods. That is the thread that calls these three methods locks object holding the lock object's monitor.

6. wait () method

This method is called the thread exits the monitor and enters a wait state until the other thread enters the same monitor and calls notify () method.

7.notify( )

Waiting for a notification (which belongs to the object) monitor (s) waiting for the end of the thread. That wake up a waiting thread monitor (held by the current thread).

8.notifyAll()

Notification wait (which belongs to the object) monitor all threads waiting for the end. That wake up all waiting for (the current thread held) monitor thread.

Fifth, thread collaborative example - producers and consumers (bakery)

1. Take a look at the scene bakery

① store cupboard used to store bread;

② baked bread baker responsible for the cabinet in place;

③ man in charge of the store cupboard of bread sold;

2. Bakery will encounter two problems

① cupboard full of new bread did not put place;

② cupboard empty, but still selling bread in.

3. Solutions to the problem

① Check the master cabinet, if not full cabinet into bread, bread notify folks have to sell, if the cupboard full master suspend work until you receive notification man can put bread.

② folks checking cupboards, cabinets if not empty bread sales, notify the master can put bread, if the cupboard empty man suspend work until you receive notification master bread to sell.

4. The sample code

//面包柜
public class Cupboard {

	private int cap;// 柜子容量
	private int size;// 柜子实际存储量

	public Cupboard(int cap) {
		this.cap = cap;
	}

	public synchronized void add() {// 向柜子里面放面包
		while (isFull()) {// 面包师要判断柜子是否满了,满了的话就要等待。对于有多个面包师,不可用if。
			System.out.println(Thread.currentThread().getName() + "柜子已经放满了,有" + size + "个面包,等待中...");
			try {
				this.wait();// this为锁对象,通过其方法让他等待
				System.out.println("销售员被唤醒");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		size++;
		System.out.println(Thread.currentThread().getName() + "向柜子里面放入面包:目前柜子有:(" + size + ")个面包");
		this.notifyAll();// 唤醒所有的销售员,通知卖货。
		Thread.yield();// 给其他线程机会

	}

	public synchronized void remove() {// 从柜子里面取面包
		while (isEmpty()) {// 面包师要判断柜子是否满了,满了的话就要通知销售员售卖,等柜子不空的时候放面包
			System.out.println(Thread.currentThread().getName() + "柜子已经没有面包了");
			try {
				this.wait();
				System.out.println("面包师被唤醒");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		size--;
		System.out.println(Thread.currentThread().getName() + "向柜子里面取走面包:目前柜子有:(" + size + ")个面包");
		this.notifyAll();// 唤醒所有的销售员,通知卖货。
		Thread.yield();// 给其他线程机会
	}

	public boolean isFull() {// 柜子是否满了
		return cap == size;
	}

	public boolean isEmpty() {// 柜子是否空了
		return size == 0;
	}

}
//面包师和销售员
public class MakeAndSale {
	public static void main(String[] args) {
		Cupboard cb = new Cupboard(5);
		for (int i = 1; i < 10; i++) { // 有九个面包师和销售员
			new Thread("面包师" + i + ">") {// 一个线程是面包师进行不断制作面包的操作
				public void run() {
					for (int i = 1; i < 100; i++) {
						cb.add();
					}
				};
			}.start();
			new Thread("销售员" + i + ">") {// 一个线程是销售员师进行不断销售面包的操作
				public void run() {
					for (int i = 0; i < 100; i++) {
						cb.remove();
					}
				};
			}.start();
		}
	}
}

5. operation result

 

Published 74 original articles · won praise 32 · views 9985

Guess you like

Origin blog.csdn.net/qq_41629684/article/details/104311587