Use the Lockers class in Java multithreading concurrency to lock multithreaded shared resources _java

Source: Internet
Author: User

Copy Code code as follows:

Package Com.yao;

Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.Future;
Import Java.util.concurrent.locks.Lock;
Import Java.util.concurrent.locks.ReadWriteLock;
Import Java.util.concurrent.locks.ReentrantLock;
Import Java.util.concurrent.locks.ReentrantReadWriteLock;

/**
* Lockers
* In multithreaded programming an important concept is locking, if a resource is shared by multiple threads, in order to ensure the integrity of the data,
* A shared resource needs to be locked for transactional operations to ensure that only one thread can operate on the resource while doing a transactional operation.
* Thus ensuring the integrity of the data. Prior to 5.0, the locking function was implemented by the Synchronized keyword.
*/
public class Lockers {

/**
* Test the use of lock. Use lock in a method to avoid using the Synchronized keyword.
*/
public static class Locktest {

Lock lock = new Reentrantlock ();//Lock
Double value = 0d; Value
int addtimes = 0;

/**
* Add value, the operation of the method is divided into 2 steps and interdependent, and must be implemented in a transaction
* So the method must be synchronized, and the previous practice was to use the Synchronized keyword in the method declaration.
*/
public void AddValue (double v) {
Lock.lock ()//Get Lock
System.out.println ("Locktest to AddValue:" + V + ""
+ System.currenttimemillis ());
try {
Thread.Sleep (1000);
catch (Interruptedexception e) {
}
This.value + V;
this.addtimes++;
Lock.unlock ()/release lock
}

Public double GetValue () {
return this.value;
}
}
public static void Testlocktest () throws exception{
Final Locktest locktest = new Locktest ();
New Task 1, calling the Locktest AddValue method
Runnable Task1 = new Runnable () {
public void Run () {
Locktest.addvalue (55.55);
}
};
New Task 2, calling the Locktest GetValue method
Runnable task2 = new Runnable () {
public void Run () {
System.out.println ("Value:" + locktest.getvalue ());
}
};
New Task Execution Service
Executorservice Cachedservice = Executors.newcachedthreadpool ();
Future Future = null;
Execute the Task 13 times at the same time, because the AddValue method uses the lock mechanism, it essentially sequentially executes
for (int i=0; i<3; i++) {
Future = Cachedservice.submit (TASK1);
}
Wait until the last task 1 is done
Future.get ();
Then execute task 2, output the result
Future = Cachedservice.submit (TASK2);
Close task execution service after waiting for task 2 to finish
Future.get ();
Cachedservice.shutdownnow ();
}

/**
* Readwritelock built-in two lock, one is read lock, one is write lock.
* Multiple threads can get read lock at the same time, but only one thread can get the write lock,
* And when the write lock is locked, no thread can get lock. The methods provided by Readwritelock are:
* Readlock (): Returns a read lock
* Writelock (): Returns a write lock, this lock is exclusive.
* Readwritelocktest is well suited for reading and writing similar files.
* Reading can be read at the same time, but can not write, writing can neither write nor read.
*/
public static Class readwritelocktest{
Lock
Readwritelock lock = new Reentrantreadwritelock ();
Value
Double value = 0d;
int addtimes = 0;

/**
* Add value, do not allow multiple threads to enter the method at the same time
*/
public void AddValue (double v) {
Get Writelock and lock
Lock Writelock = Lock.writelock ();
Writelock.lock ();
System.out.println ("Readwritelocktest to AddValue:" + V + ""
+ System.currenttimemillis ());
try {
Thread.Sleep (1000);
catch (Interruptedexception e) {
}
try {
Do the work of writing
This.value + V;
this.addtimes++;
finally {
Release Writelock Lock
Writelock.unlock ();
}
}
/**
* Access to information. When a thread calls the AddValue method, the information that GetInfo obtains may not be correct.
* Therefore, you must also ensure that the method does not invoke the AddValue method when it is invoked.
*/
Public String GetInfo () {
Get Readlock and lock
Lock Readlock = Lock.readlock ();
Readlock.lock ();
System.out.println ("Readwritelocktest to GetInfo")
+ System.currenttimemillis ());
try {
Thread.Sleep (1000);
catch (Interruptedexception e) {
}
try {
Do the work of reading
return this.value + ":" + this.addtimes;
finally {
Release Readlock
Readlock.unlock ();
}
}
}

public static void Testreadwritelocktest () throws exception{
Final Readwritelocktest readwritelocktest = new Readwritelocktest ();
New Task 1, calling the Locktest AddValue method
Runnable task_1 = new Runnable () {
public void Run () {
Readwritelocktest.addvalue (55.55);
}
};
New Task 2, calling the Locktest GetValue method
Runnable task_2 = new Runnable () {
public void Run () {
System.out.println ("info:" + readwritelocktest.getinfo ());
}
};
New Task Execution Service
Executorservice cachedservice_1 = Executors.newcachedthreadpool ();
Future future_1 = null;
Perform 5 tasks at the same time, where the first 2 tasks are task_1 and the last two tasks are task_2
for (int i=0; i<2; i++) {
Future_1 = Cachedservice_1.submit (task_1);
}
for (int i=0; i<2; i++) {
Future_1 = Cachedservice_1.submit (task_2);
}
The last task is task_1.
Future_1 = Cachedservice_1.submit (task_1);
The order of execution of these 5 tasks should be:
The first task_1 is executed first, and the second task_1 is executed; this is because it cannot be written at the same time, so it must wait.
Then 2 task_2 are executed at the same time, because they can't read when they're written, so they wait for the end of the writing.
And because they can be read at the same time, they execute simultaneously
The last task_1 is executed again. This is because in the reading time, also can not write, so must wait for the completion of the reading before writing.

Waiting for the last task_2 to be done.
Future_1.get ();
Cachedservice_1.shutdownnow ();
}

public static void Main (string[] args) throws exception{
Lockers.testlocktest ();
System.out.println ("---------------------");
Lockers.testreadwritelocktest ();
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.