代码示例:java.util.concurrent.locks.Lock

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

/**
 * @author kent 2013-3-11上午11:55:28
 */
public class PlayLock implements Runnable {

    private Bean bean;

    public PlayLock(Bean bean) {
        super();
        this.bean = bean;
    }

    public void run() {
        for (int j = 0; j < 100; j++) {
            bean.increment();
        }

    }

    private static final class Bean {
        private int  i          = 0;

        private Lock lockObject = new ReentrantLock(); //如果是 new ReentrantLock(true)则代表锁是“公平”的,即先求锁者先得锁,避免“饿死”

        public void increment() {
            try {
                lockObject.lock(); //加锁
                doIncrement();
            } finally {
                lockObject.unlock(); //释放锁,要放在finally块里
            }

        }

        private void doIncrement() {
            int k = i;
            k = k + 1;
            doSleep();
            i = k;
            System.out.println(Thread.currentThread().getName() + ": i = " + i);
        }

        private void doSleep() {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) {
        Bean bean = new Bean();
        Thread t1 = new Thread(new PlayLock(bean));
        Thread t2 = new Thread(new PlayLock(bean));

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

}


Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.