java線程--重入鎖

重入鎖re-entrant-lock

public class Test {

    static class Reenter implements Runnable {

        public static ReentrantLock lock = new ReentrantLock();
        public static int i = 0;

        @Override
        public void run() {

            for (int j = 0; j < 4; j++) {
                lock.lock();
                lock.lock();
                //容許多重鎖.
                try {
                    i++;
                } finally {
                    lock.unlock();
                    lock.unlock();
                }
            }
        }

    }

    public static void main(String[] args) throws InterruptedException {

        Reenter r = new Reenter();
        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(Reenter.i);
    }

}
相關文章
相關標籤/搜索