Saturday, 11 January 2014

Advanced Java_ Multi-threading Part 10 - Re-entrant Locks


===
package Demo12;

import Demo11.Processor;

/**
 * Title -- Advanced Java_ Multi-threading Part 10 - Re-entrant Locks
 *
 * @author Dharmaraj.Net
 */
public class App {

    public static void main(String[] args) throws Exception{
        final Runner runner = new Runner();

        Thread t1 = new Thread(new Runnable() {

            public void run() {
                try {
                    runner.firstThread();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        });

        Thread t2 = new Thread(new Runnable() {

            public void run() {
                try {
                    runner.secondThread();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();
       
        runner.finished();
    }

}
===========
package Demo12;

import java.util.Date;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Runner {

    private int count = 0;
    // ReentrantLock Means once any thread hold the lock of ReentrantLock will
    // count how many time it take the lock and need to unlock the same time
    private Lock lock = new ReentrantLock();
    private Condition cond = lock.newCondition();

    private void increment() {
        for (int i = 0; i < 10000; i++) {
            count++;
        }
    }

    public void firstThread() throws InterruptedException {
        lock.lock();
        System.out.println("Waiting..");
        cond.await();
        System.out.println("Worken up..");
        try {
            increment();
        } finally {
            lock.unlock();
        }

    }

    public void secondThread() throws InterruptedException {
        Thread.sleep(1000);
        lock.lock();
        System.out.println("Press the return key...");
        new Scanner(System.in).nextLong();
        System.out.println("Got return key...");
        cond.signal();
        try {
            increment();
        } finally {
            lock.unlock();
        }
    }

    public void finished() {
        System.out.println("Count is " + count);
    }
}
=========
 

No comments:

Post a Comment