java 5 Lock

 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

posted on 2014-10-26 20:39  TroyZ  阅读(214)  评论(0编辑  收藏  举报