1 import java.util.concurrent.locks.Lock;
2 import java.util.concurrent.locks.ReentrantLock;
3
4
5 /**
6 * java5的线程锁技术
7 * Lock比传统线程模型中的synchronized方式更加面向对象,与生活中的锁类似。
8 * 锁本身也应该是一个对象。两个线程执行的代码片段要实现同步互斥的效果,它们必须
9 * 用在同一个Lock对象。锁是上在代表要操作的资源的类的内部方法中,而不是线程代码中。
10 * @author LiTaiQing
11 */
12 public class LockTest {
13
14 public static void main(String[] args){
15 new LockTest().init();
16 }
17
18 private void init(){
19 /**
20 * 内部类访问局部变量,局部变量要加final
21 * 若此代码放在main中会报错,因为静态代码块不能访问内部类
22 */
23 final Outputer outputer = new Outputer();
24 new Thread(new Runnable(){
25 @Override
26 public void run() {
27 while(true){
28 outputer.output("zhangxiaoxiang");
29 }
30 }
31 }).start();
32 new Thread(new Runnable(){
33 @Override
34 public void run() {
35 while(true){
36 outputer.output("lihuoming");
37 }
38 }
39 }).start();
40 }
41
42 static class Outputer{
43 Lock lock = new ReentrantLock();
44 public void output(String name){
45 int len = name.length();
46 lock.lock();
47 try{
48 for(int i = 0; i < len ; i++){
49 System.out.print(name.charAt(i));
50 }
51 System.out.println();
52 }finally{
53 lock.unlock();
54 }
55 }
56 }
57 }