首页 > 编程语言 > 详细

java 5 Lock

时间:2014-10-26 21:06:37      阅读:307      评论:0      收藏:0      [点我收藏+]
 1 import java.util.concurrent.locks.Lock;
 2 import java.util.concurrent.locks.ReentrantLock;
 3 
 4 public class LookTest
 5 {
 6     public static void main(String[] args)
 7     {
 8         runThread("hello");
 9         runThread("world");
10     }
11     
12     private static void runThread(final String str)
13     {
14         new Thread(new Runnable()
15         {
16             public void run()
17             {
18 //                outPut(str);
19                 outPut2(str);
20             }
21         }).start();
22     }
23 
24     private static void outPut(String str)
25     {
26         // 使用synchronized对代码加锁
27         synchronized (LookTest.class)
28         {
29             for(int i = 0; i < str.length(); i++)
30             {
31                 System.out.print(str.charAt(i));
32             }
33             System.out.println();
34         }
35     }
36 
37     private static Lock lock = new ReentrantLock();
38     private static void outPut2(String str)
39     {
40         // 使用lock锁
41         lock.lock();
42         for(int i = 0; i < str.length(); i++)
43         {
44             System.out.print(str.charAt(i));
45         }
46         System.out.println();
47         lock.unlock();
48     }
49 }

输出结果:

world
hello

java 5 Lock

原文:http://www.cnblogs.com/java-koma/p/4052691.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!