Use ReentrantLock to control resource - Java Thread

Java examples for Thread:Lock

Description

Use ReentrantLock to control resource

Demo Code



import java.util.Date;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest
{
    //from w  ww .jav  a  2s.com
    private static class Stub1
    {
        private static ReentrantLock lock = new ReentrantLock();
        
        public void test()
        {
            try
            {
                lock.lock();
                System.out.println(Thread.currentThread().getName() + "Parent-before sleep." + (new Date()));
                Thread.currentThread().sleep(3000l);
                System.out.println(Thread.currentThread().getName() + "Parent-after sleep." + (new Date()));
                t1();
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            finally
            {
                lock.unlock();
            }
        }
        
        public void t1()
        {
            try
            {
                lock.lock();
                System.out.println(Thread.currentThread().getName() + "before sleep." + (new Date()));
                Thread.currentThread().sleep(3000l);
                System.out.println(Thread.currentThread().getName() + "after sleep." + (new Date()));
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            finally
            {
                lock.unlock();
            }
        }
    }
    
    private void testMutexAndReentrant()
    {
        Thread t1 = new Thread()
        {
            
            @Override
            public void run()
            {
                Stub1 s1 = new Stub1();
                s1.test();
            }
            
        };
        t1.setName("t1-");
        Thread t2 = new Thread()
        {
            
            @Override
            public void run()
            {
                Stub1 s1 = new Stub1();
                s1.test();
            }
            
        };
        t2.setName("t2-");
        t1.start();
        t2.start();
    }
    
    public static void main(String[] args)
    {
        ReentrantLockTest test = new ReentrantLockTest();
        test.testMutexAndReentrant();
    }
}

Related Tutorials