package com.thinker.common.thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by root on 7/20/16.
 * 练习使用重入锁（ReentranLock）
 */
public class ReentrantLockTest {
    public static class Domain {
        private static int i = 0;
        private static ReentrantLock lock = new ReentrantLock(false);
        public static int addI() {
            lock.lock();
            try {
                i++;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
            return i;
        }
    }

    public  class Thread1 extends Thread {
        @Override
        public void run() {
               for(int i=0;i<20;i++){
                   System.out.println(Thread.currentThread().getName()+"\t"+Domain.addI());
               }
        }
    }

    public  class Thread2 extends Thread {
        @Override
        public void run() {
            for(int i=0;i<20;i++){
                System.out.println(Thread.currentThread().getName()+"\t"+Domain.addI());
            }
        }
    }


    public static void main(String[] args) {
        ReentrantLockTest test = new ReentrantLockTest();
        ReentrantLockTest.Thread1 thread1 = test.new Thread1();
        Thread2 thread2 = test.new Thread2();
        thread1.start();
        thread2.start();
    }
}

