/**
 * 对象锁: 多个线程访问同一个实例对象会对该实例对象的锁进行竞争,谁先拿到谁就能操作上锁的资源
 * 
 * 以下是三种对象锁的设置方式
 */

public class ObjectLock {
    private Object lock = new Object();

    /**
     * 1.锁住非静态变量
     *
     * @throws InterruptedException
     */
    public void lockObjectField() throws InterruptedException {
        synchronized (lock) {
            System.out.println(Thread.currentThread().getName());
            Thread.sleep(2 * 1000);
        }
    }

    /**
     * 2.锁住 this 对象 this 就是当前对象实例
     *
     * @throws InterruptedException
     */
    public void lockThis() throws InterruptedException {
        synchronized (this) {
            System.out.println(Thread.currentThread().getName());
            Thread.sleep(2 * 1000);
        }
    }

    /**
     * 3.直接锁住非静态方法
     *
     * @throws InterruptedException
     */
    public synchronized void methodLock() throws InterruptedException {
        System.out.println(Thread.currentThread().getName());
        Thread.sleep(2 * 1000);
    }

    public static void main(String[] args) {
        //创建线程共享的资源
        ObjectLock objectLock = new ObjectLock();
        for (int i = 0; i < 5; i++) {
            //创建多线程访问同一个对象
            Thread worker = new Thread(new ObjectLockWorker(objectLock));
            worker.setName("geek996-" + i);
            worker.start();
        }
    }

    public static class ObjectLockWorker implements Runnable {
        ObjectLock objectLock;
        public ObjectLockWorker(ObjectLock objectLock) {
            this.objectLock = objectLock;
        }

        @Override
        public void run() {
            //访问锁资源
            try {
                // 方式 1
                objectLock.lockObjectField();
                //方式 2
                objectLock.lockThis();
                // 方式 3
//                objectLock.methodLock();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

 

Rick  11浏览  0评论  2020-10-12

上一篇