ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future;ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReadWriteLock;ImportJava.util.concurrent.locks.ReentrantLock;ImportJava.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, * in the transactional operation of the need to lock the shared resources, so that when doing transactional operations only one thread can operate the resources, * This ensures the integrity of the data. Before 5.0, locked functionality was implemented by the Synchronized keyword. */ Public classLockers {/*** Test the use of lock. Use lock in your method to avoid using the Synchronized keyword. */ Public Static classLocktest {lock lock=NewReentrantlock ();//Lock Doublevalue = 0d;//value intAddtimes = 0; /*** Add value, the operation of the method is divided into 2 steps, and interdependent, must be implemented in a transaction * So the method must be synchronized, the previous practice is to use the Synchronized keyword in the method declaration. */ Public voidAddValue (Doublev) {lock.lock ();//Get lockSystem.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 DoubleGetValue () {return This. Value; } } Public Static voidTestlocktest ()throwsexception{FinalLocktest locktest =Newlocktest (); //New Task 1, calling Locktest's AddValue methodRunnable Task1 =NewRunnable () { Public voidrun () {Locktest.addvalue (55.55); } }; //New Task 2, calling Locktest's GetValue methodRunnable Task2 =NewRunnable () { Public voidrun () {System.out.println ("Value:" +Locktest.getvalue ()); } }; //New Task Execution ServiceExecutorservice Cachedservice =Executors.newcachedthreadpool (); Future=NULL; //perform the task 13 times at the same time, because the AddValue method uses the lock mechanism, so it is actually executed sequentially for(inti=0; i<3; i++) { future=Cachedservice.submit (TASK1); } //wait for the last task 1 to be executedFuture.get (); //perform task 2 again, output resultFuture =Cachedservice.submit (TASK2); //After you wait for Task 2 to finish executing, close the task execution serviceFuture.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 write lock, * and the write lock is locked, no thread can get lock. Readwritelock provides methods such as: * Readlock (): Returns a read lock * Writelock (): Returns a write lock, which is exclusive. * The readwritelocktest is well suited for handling similar file read and write operations. * Reading can be read at the same time, but cannot write, when writing, neither write nor read. */ Public Static classreadwritelocktest{//LockReadwritelock lock =NewReentrantreadwritelock (); //value DoubleValue =0d; intAddtimes = 0; /*** Increase value, do not allow multiple threads to enter the method at the same time*/ Public voidAddValue (Doublev) {//get Writelock and lockLock 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 LockWritelock.unlock (); } } /*** Get information. When the thread is calling the AddValue method, the GetInfo information may be incorrect. * Therefore, it is also necessary to ensure that the method is called when there is no method in calling the AddValue method. */ PublicString GetInfo () {//get Readlock and lockLock 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 ReadlockReadlock.unlock (); } } } Public Static voidTestreadwritelocktest ()throwsexception{FinalReadwritelocktest readwritelocktest =Newreadwritelocktest (); //New Task 1, calling Locktest's AddValue methodRunnable Task_1 =NewRunnable () { Public voidrun () {Readwritelocktest.addvalue (55.55); } }; //New Task 2, calling Locktest's GetValue methodRunnable task_2 =NewRunnable () { Public voidrun () {System.out.println ("INFO:" +readwritelocktest.getinfo ()); } }; //New Task Execution ServiceExecutorservice cachedservice_1 =Executors.newcachedthreadpool (); Future Future_1=NULL; //perform 5 tasks at the same time, with the first 2 tasks being task_1 and the last two tasks task_2 for(inti=0; i<2; i++) {future_1=Cachedservice_1.submit (task_1); } for(inti=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 for these 5 tasks should be://The first Task_1 executes first, and the second task_1 executes; 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; this is because at the time of writing, cannot read, therefore all waits writes the end,//and because they can read at the same time, they execute simultaneously//The last Task_1 is executed again. This is because at the time of reading, also cannot write, therefore must wait for the reading to finish, can write. //waiting for the last task_1 to be executed .Future_1.get (); Cachedservice_1.shutdownnow (); } Public Static voidMain (string[] args)throwsexception{lockers.testlocktest (); System.out.println ("---------------------"); Lockers.testreadwritelocktest (); }}
Transfer from http://blog.csdn.net/huang_xw/article/details/7090177
Use < transfer of Java multi-thread lock;