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 will need to be locked for transactional operations to ensure that only one thread is able to operate on the resource while the transaction is being performed, thus protecting The completeness of the evidence data.
Prior to 5.0, the locking function was implemented by the Synchronized keyword. * * public class Lockers {/** * Test lock usage.
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;
/** * Adds value, the operation of which 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 calls the Locktest AddValue method Runnable Task1 = new Runnable () {public void run () {locktest.addvalue (55.55);
}
}; New Task 2, call 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 executed future.get ();
Then perform task 2, the output result future = Cachedservice.submit (TASK2);
Wait for Task 2 to finish, close the Task Execution Service 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 oneThe thread can get a write lock, * and the lock is locked, and no thread will get lock.
Readwritelock provides the following methods: * 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; /** * Adds value, does not allow multiple threads to enter the method at the same time */public void AddValue (double v) {//Get Writelock and lock lock Writelock = LOCK.W
Ritelock ();
Writelock.lock ();
System.out.println ("Readwritelocktest to AddValue:" + V + "" + System.currenttimemillis ());
try {thread.sleep (1000);
The catch (Interruptedexception e) {} try {//write work This.value + = V;
this.addtimes++;
finally {//release Writelock lock Writelock.unlock (); }/** * Get 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);
The catch (Interruptedexception e) {} try {//Do read work return this.value + ":" + this.addtimes;
finally {//release readlock readlock.unlock (); }} public static void Testreadwritelocktest () throws exception{final Readwritelocktest readwritelocktest = new
Readwritelocktest (); New Task 1, call Locktest AddValue method Runnable task_1 = new Runnable () {public void run () {Readwritelocktest.addvalue (55
.55);
}
}; New Task 2, call 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 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:///First Task_1 first, second task_1 to be 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 are not readable at the time of writing, so they wait for the end of the write,//And because they can be read at the same time, they execute//the last Task_1 to execute.
This is because in the reading time, also can not write, so must wait for the completion of the reading before writing.
Wait for the last task_2 to be executed future_1.get ();
Cachedservice_1.shutdownnow ();
public static void Main (string[] args) throws exception{lockers.testlocktest ();
System.out.println ("---------------------");
Lockers.testreadwritelocktest (); }
}