JDK 5.0 특성-스 레 드 잠 금 잠 금

34925 단어 Lock
출처:http://www.cnblogs.com/taven/archive/2011/12/17/2291470.html
  1 import java.util.concurrent.ExecutorService;
  2 
  3 import java.util.concurrent.Executors;
  4 
  5 import java.util.concurrent.Future;
  6 
  7 import java.util.concurrent.locks.Lock;
  8 
  9 import java.util.concurrent.locks.ReadWriteLock;
 10 
 11 import java.util.concurrent.locks.ReentrantLock;
 12 
 13 import java.util.concurrent.locks.ReentrantReadWriteLock;
 14 
 15  
 16 
 17  
 18 
 19 /**
 20 
 21            ,          ,              ,          ,         
 22 
 23          ,                    ,           . J2SE5.0        
 24 
 25  synchronized       .          J2SE 5.0         ,      、    .
 26 
 27       :
 28 
 29      J2SE5.0     java.util.concurrent.locks.lock   ,           :
 30 
 31     1.ReentrantLock    Lock  ,         synchronized   .
 32 
 33     2.ReentrantLock lock     ,              ,         ,        1;           ,     ,       1;           ,           ,        
 34 
 35  ,         1.
 36 
 37     3.ReentrantLock unlock     ,            ,        1,         0,    .             ,     .
 38 
 39     4.ReadWriteLock     Lock   ,      .        ReentrantReadWriteLock
 40 
 41     5.ReentrantReadWriteLock writeLock             ,       ,                .
 42 
 43     6.ReentrantReadWriteLock readLock            ,       ,               ,         .   
 44 
 45 */
 46 
 47 public class Lockers {
 48 
 49        /**  Lock   .      Lock,      synchronized   */
 50 
 51        public static class LockTest{
 52 
 53               Lock lock = new ReentrantLock();// 
 54 
 55               double value = 0d; // 
 56 
 57               int addtimes = 0;
 58 
 59               /**
 60 
 61                *   value  ,        2 ,      ,          
 62 
 63                *          ,              synchronized   
 64 
 65                */
 66 
 67               public void addValue(double v){
 68 
 69                      lock.lock();//   
 70 
 71                      System.out.println("LockTest to addValue: " + v + " " + System.currentTimeMillis());
 72 
 73                      try {
 74 
 75                             Thread.sleep(1000);
 76 
 77                      }catch(InterruptedException e){
 78 
 79                      }
 80 
 81                      this.value += v;
 82 
 83                      this.addtimes++;
 84 
 85                      lock.unlock();
 86 
 87               }
 88 
 89               public double getValue(){
 90 
 91                      return this.value;
 92 
 93               }
 94 
 95        }
 96 
 97        public static void testLockTest() throws Exception{
 98 
 99               final LockTest lockTest = new LockTest();
100 
101               //    1,  lockTest addValue  
102 
103               Runnable task1 = new Runnable(){
104 
105                      public void run(){
106 
107                             lockTest.addValue(55.55);
108 
109                      }
110 
111               };
112 
113               //    2,  lockTest getValue  
114 
115                Runnable task2 = new Runnable(){
116 
117                       public void run(){
118 
119                              System.out.println("value: " + lockTest.getValue());
120 
121                       }
122 
123                };
124 
125                //        
126 
127                ExecutorService cachedService = Executors.newCachedThreadPool();
128 
129                Future future = null;
130 
131                //      1  ,   addValue        ,  ,        
132 
133                for(int i=0;i<3;i++){
134 
135                       future = cachedService.submit(task1);
136 
137                }
138 
139                future.get();//        1    
140 
141                future = cachedService.submit(task2);//     2,    
142 
143                future.get();//    2    ,        
144 
145                cachedService.shutdownNow();
146 
147        }
148 
149        /**
150 
151         * ReadWriteLock    Lock,     Lock,     Lock
152 
153         *            Lock,            Lock
154 
155         *     Lock    ,         Lock.ReadWriteLock      :
156 
157         * readLock():      Lock
158 
159         * writeLock():      lock, lock    
160 
161         * ReadWriteLockTest              
162 
163         *          ,     ,          ,    
164 
165         */
166 
167        public static class ReadWriteLockTest{
168 
169               ReadWriteLock lock = new ReentrantReadWriteLock();// 
170 
171               double value = 0d; // 
172 
173               int addtimes = 0;
174 
175               /**  value  ,              */
176 
177               public void addValue(double v){
178 
179                      //  writeLock   
180 
181                      Lock writeLock = lock.writeLock();
182 
183                      writeLock.lock();
184 
185                      System.out.println("ReadWriteLockTest to addValue: " + v + " " + System.currentTimeMillis());
186 
187                      try{
188 
189                             Thread.sleep(1000);
190 
191                      }catch(InterruptedException e){                        
192 
193                      }
194 
195                      try{
196 
197                             //     
198 
199                             this.value += v;
200 
201                             this.addtimes++;
202 
203                      }finally{
204 
205                             writeLock.unlock();
206 
207                      }
208 
209               }
210 
211               /**
212 
213                *    .       addValue   ,getInfo            .
214 
215                *  ,             ,       addValue  .
216 
217                */
218 
219               public String getInfo(){
220 
221                      //   readLock   
222 
223                      Lock readLock = lock.readLock();
224 
225                      readLock.lock();
226 
227                      System.out.println("ReadWriteLockTest to getInfo "+System.currentTimeMillis());
228 
229                      try{
230 
231                             Thread.sleep(1000);
232 
233                      }catch(InterruptedException e){
234 
235                      }
236 
237                      try{
238 
239                             return this.value + " : " + this.addtimes;//     
240 
241                      }finally{
242 
243                             readLock.unlock();//  readLock
244 
245                      }
246 
247               }
248 
249        }
250 
251        public static void testReadWriteLockTest() throws Exception{
252 
253               final ReadWriteLockTest readWriteLockTest = new ReadWriteLockTest();
254 
255               //    1,  lockTest addValue  
256 
257               Runnable task_1 = new Runnable(){
258 
259                      public void run(){
260 
261                             readWriteLockTest.addValue(55.55);
262 
263                      }
264 
265               };
266 
267               //    2,  lockTest getValue  
268 
269               Runnable task_2 = new Runnable(){
270 
271                      public void run(){
272 
273                             System.out.println("info " + readWriteLockTest.getInfo());
274 
275                      }
276 
277               };
278 
279               //          
280 
281               ExecutorService cachedService_1 = Executors.newCachedThreadPool();
282 
283               Future future_1 = null;
284 
285               //    5   ,   2      1,        2
286 
287               for(int i=0;i<2;i++){
288 
289                      future_1 = cachedService_1.submit(task_1);
290 
291               }
292 
293               for(int i=0;i<2;i++){
294 
295                      future_1 = cachedService_1.submit(task_2);
296 
297               }
298 
299               //         1
300 
301               future_1 = cachedService_1.submit(task_1);
302 
303               // 5           
304 
305               //     1   ,     1   ;         ,     
306 
307               //      2    ;         ,    ,        
308 
309               //        ,        
310 
311               //      1   .         ,    ,          ,
312 
313               //   .        2    
314 
315               future_1.get();
316 
317               cachedService_1.shutdownNow();
318 
319        }
320 
321        public static void main(String... args)throws Exception{
322 
323               Lockers.testLockTest();
324 
325               System.out.println("--------------------------");
326 
327               Lockers.testReadWriteLockTest();
328 
329        }
330 
331 }
332 
333 /**
334 
335  * ReentrantReadWriteLock        :
336 
337  * This class does not impose a reader or writer preference ordering for lock access.
338 
339  * However, it does support an optional fairness policy.
340 
341  * When constructed as fair, threads contend for entry using an approximatelyarrival-order policy.
342 
343  * When the write lock is released either the longest-waiting single writer will beassigned the write lock, or if there is a reader waiting longer than any writer, theset of readers will be assigned the read lock.
344 
345  * When constructed as non-fair, the order of entry to the lock need not be in arrivalorder.
346 
347  * In either case, if readers are active and a writer enters the lock then nosubsequent readers will be granted the read lock until after that writer has acquiredand released the write lock.
348 
349 */

좋은 웹페이지 즐겨찾기