1. 程式人生 > >多執行緒reentrantLock重入鎖案例分析

多執行緒reentrantLock重入鎖案例分析

public class Runner {

    private int count = 0;
    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("Woken 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).nextLine();
        System.out.println("Got return key!");
        cond.signal();
        try {
            increment();
        } finally {
            //should be written to unlock Thread whenever signal() is called
            lock.unlock();
        }
    }

    public void finished() {
        System.out.println("Count is: " + count);
    }
}
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 ignored) {
                }
            }
        });

        Thread t2 = new Thread(new Runnable() {
            public void run() {
                try {
                    runner.secondThread();
                } catch (InterruptedException ignored) {
                }
            }
        });

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

}

執行app類執行結果如下

Waiting .... Press the return key! 1 Got return key! Woken up! Count is: 20000

其中1是自定義輸入的內容 不然會堵塞程式碼

  1. 首先在APP類中加上join方法是為了執行完t1和t2後再執行 finish方法
  2. 在runner類中secondThread中加入Thread.sleep(1000);是為了先執行t1執行緒
  3. 當註釋掉runner類中secondThread方法的 // cond.signal()時;執行會阻塞 ,不會執行Got return key!後面的內容 只是因為在app類中t1.join()方法 使join執行緒不執行完就不會執行finish方法 註釋掉就會列印 Waiting .... Press the return key! 1 Got return key! Count is: 10000