多线程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

猜你喜欢

转载自blog.csdn.net/faker____/article/details/82967043