---
title: "线程学习二，ReentrantLock.Lock实现线程互斥"
author: "GreatNeyo"
date: "2010-07-26T12:57:44Z"
tags: ["Java", "thread"]
categories: ["编程语言"]
slug: "reentrantlock-lock"
draft: false
lastmod: "2010-07-26T13:05:04Z"
id: 721317
url: "https://greatneyo.iteye.com/blog/721317"
---

```java

/*
 ReentrantLock.Lock实现线程互斥
 */

package threadTest;

import java.util.concurrent.locks.ReentrantLock;

/**
 *ReentrantLock 的效率比
 */
public class LockThread {

    ReentrantLock lock1 = new ReentrantLock();
//    ReentrantLock lock2 = new ReentrantLock();
    class LockInitFirst implements Runnable{

        public void run() {
            lock1.lock();
            try {
                System.out.println("lock1");
                Thread.sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                lock1.unlock();
            }
        }

    }
    class LockInitSecond implements Runnable{

        public void run() {
            lock1.lock();
            try {
                System.out.println("lock2");
                Thread.sleep(2000);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                lock1.unlock();
            }
        }
    }
    private LockInitFirst getLockInitFirst(){
        LockInitFirst lif = new LockInitFirst();
        return lif;
    }
    private LockInitSecond getLockInitSecond(){
        LockInitSecond lis = new LockInitSecond();
        return lis;
    }
    public static void main(String[] args) {
        LockThread lt = new LockThread();
//   LockInitFirst lifirst = lt.new LockInitFirst();可以用这种方式new出一个内部类
        Thread th1 = new Thread(lt.getLockInitFirst());
        Thread th2 = new Thread(lt.getLockInitSecond());
        th1.start();
        th2.start();
    }
}

```