Java thread locking object Lock- 08-- learning more perfect synchronization approach

Lock is the interface under java.util.concurrent.locks bag, Lock implementations provide the use of synchronized methods and statements available to a wider range of lock operation, it can in a more elegant way to handle thread synchronization problem, we take Java threads ( an example of ii) is sychronized and simple implementation at the same effect, as follows:
 

public class LockTest {
	public static void main(String[] args) {
		final Outputter1 output = new Outputter1();
		new Thread() {
			public void run() {
				output.output("zhangsan");
			};
		}.start();		
		new Thread() {
			public void run() {
				output.output("lisi");
			};
		}.start();
	}
}
class Outputter1 {
	private Lock lock = new ReentrantLock();// 锁对象
	public void output(String name) {
		// TODO 线程输出方法
		lock.lock();// 得到锁
		try {
			for(int i = 0; i < name.length(); i++) {
				System.out.print(name.charAt(i));
			}
		} finally {
			lock.unlock();// 释放锁
		}
	}
}

         This realization and sychronized same synchronization effect, be noted that, or statement block after the code executing the lock is automatically released by sychronized modified method, but with Lock we need to manually release the lock, so in order to ensure the lock is finally released ( abnormal situation), should be placed in the exclusive area try, release the lock on the inside finally.

        If this is the Lock, then it can not be a more perfect synchronization approach, to introduce the following is read-write lock (ReadWriteLock), we will have a need, at the time of data read and write, in order to ensure consistency of data and integrity, requires reading and writing are mutually exclusive, write, and writing are mutually exclusive, but are not required to read and read mutually exclusive, so do not read and read some more exclusive performance, look no consideration exclusive situation prototype code:
 


public class ReadWriteLockTest {
	public static void main(String[] args) {
		final Data data = new Data();
		for (int i = 0; i < 3; i++) {
			new Thread(new Runnable() {
				public void run() {
					for (int j = 0; j < 5; j++) {
						data.set(new Random().nextInt(30));
					}
				}
			}).start();
		}		
		for (int i = 0; i < 3; i++) {
			new Thread(new Runnable() {
				public void run() {
					for (int j = 0; j < 5; j++) {
						data.get();
					}
				}
			}).start();
		}
	}
}
class Data {	
	private int data;// 共享数据	
	public void set(int data) {
		System.out.println(Thread.currentThread().getName() + "准备写入数据");
		try {
			Thread.sleep(20);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		this.data = data;
		System.out.println(Thread.currentThread().getName() + "写入" + this.data);
	}	
	public void get() {
		System.out.println(Thread.currentThread().getName() + "准备读取数据");
		try {
			Thread.sleep(20);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName() + "读取" + this.data);
	}
}

 

  部分输出结果:

Thread-1准备写入数据
Thread-3准备读取数据
Thread-2准备写入数据
Thread-0准备写入数据
Thread-4准备读取数据
Thread-5准备读取数据
Thread-2写入12
Thread-4读取12
Thread-5读取5

 We want to achieve mutually exclusive write and write, read and write mutually exclusive, reading and reading are mutually exclusive, adding sychronized modifier set and get methods:


public synchronized void set(int data) {...}	
public synchronized void get() {...}
部分输出结果:

Thread-0准备写入数据
Thread-0写入9
Thread-5准备读取数据
Thread-5读取9
Thread-5准备读取数据
Thread-5读取9
Thread-5准备读取数据
Thread-5读取9
Thread-5准备读取数据
Thread-5读取9

  We found that, although the exclusive write and write, read and write but also mutually exclusive, but also between reading and reading are mutually exclusive, and can not be executed concurrently, less efficient implementation code with read-write lock as follows:


class Data {	
	private int data;// 共享数据
	private ReadWriteLock rwl = new ReentrantReadWriteLock();	
	public void set(int data) {
		rwl.writeLock().lock();// 取到写锁
		try {
			System.out.println(Thread.currentThread().getName() + "准备写入数据");
			try {
				Thread.sleep(20);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			this.data = data;
			System.out.println(Thread.currentThread().getName() + "写入" + this.data);
		} finally {
			rwl.writeLock().unlock();// 释放写锁
		}
	}	
	public void get() {
		rwl.readLock().lock();// 取到读锁
		try {
			System.out.println(Thread.currentThread().getName() + "准备读取数据");
			try {
				Thread.sleep(20);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName() + "读取" + this.data);
		} finally {
			rwl.readLock().unlock();// 释放读锁
		}
	}
}

 

 部分输出结果:

Thread-4准备读取数据
Thread-3准备读取数据
Thread-5准备读取数据
Thread-5读取18
Thread-4读取18
Thread-3读取18
Thread-2准备写入数据
Thread-2写入6
Thread-2准备写入数据
Thread-2写入10
Thread-1准备写入数据
Thread-1写入22
Thread-5准备读取数据

 As can be seen from the results met our needs, this is just basic usage of the lock, the lock mechanism needs further study.

 

 

Guess you like

Origin blog.csdn.net/yuhaibao324/article/details/93149699
Recommended