精华内容
下载资源
问答
  • 自定义Lock显示锁 public interface Lock { class TimeOutException extends Exception { public TimeOutException(String message) { super(message); } } /** * 加锁 * * @throws ...

    自定义Lock显示锁

    public interface Lock {
    	class TimeOutException extends Exception {
    		public TimeOutException(String message) {
    			super(message);
    		}
    	}
    
    	/**
    	 * 加锁
    	 *
    	 * @throws InterruptedException 打断异常
    	 */
    	void lock() throws InterruptedException;
    
    	/**
    	 * 加锁
    	 *
    	 * @param mills 加锁时间
    	 * @throws InterruptedException 打断异常
    	 * @throws TimeOutException     超时异常
    	 */
    	void lock(long mills) throws InterruptedException, TimeOutException;
    
    	/**
    	 * 解锁
    	 */
    	void unlock();
    
    	/**
    	 * 获取争抢锁时被阻塞的线程
    	 *
    	 * @return 被阻塞线程的集合
    	 */
    	Collection<Thread> getBlockedThread();
    
    	/**
    	 * 获取争抢锁时被阻塞的线程的数量
    	 *
    	 * @return 被阻塞的线程的数量
    	 */
    	int getBlockedSize();
    }
    
    
    public class BooleanLock implements Lock {
    	/**
    	 * The initValue is true indicated the lock has been get.
    	 * The initValue is false indicated the lock is free (other thread can get this).
    	 */
    	private boolean initValue;
    
    	private Collection<Thread> blockedThreadCollection = new ArrayList<>();
    
    	private Thread currentThread;
    
    	public BooleanLock() {
    		this.initValue = false;
    	}
    
    	@Override
    	public synchronized void lock() throws InterruptedException {
    		// 锁已经被其他线程使用
    		while (initValue) {
    			blockedThreadCollection.add(Thread.currentThread());
    			this.wait();
    		}
    		// 锁未被使用,抢到锁立即设置initValue的值
    		this.initValue = true;
    		this.currentThread = Thread.currentThread();
    		blockedThreadCollection.remove(Thread.currentThread());
    	}
    
    	@Override
    	public synchronized void lock(long mills) throws InterruptedException, TimeOutException {
    		if (mills <= 0) {
    			lock();
    		}
    
    		long hasRemaining = mills;
    		long endTime = System.currentTimeMillis() + mills;
    		while (initValue) {
    			if (hasRemaining <= 0) {
    				throw new TimeOutException("Time Out");
    			}
    			blockedThreadCollection.add(Thread.currentThread());
    			this.wait(mills);
    			hasRemaining = endTime - System.currentTimeMillis();
    			// System.out.println(Thread.currentThread().getName() + ">>" + hasRemaining);
    		}
    		this.initValue = true;
    		this.currentThread = Thread.currentThread();
    	}
    
    	@Override
    	public synchronized void unlock() {
    		// 释放锁
    		if (Thread.currentThread() == currentThread) {
    			this.initValue = false;
    			Optional.of(Thread.currentThread().getName() + " release the lock monitor.").ifPresent(System.out::println);
    			this.notifyAll();
    		}
    	}
    
    	@Override
    	public Collection<Thread> getBlockedThread() {
    		// 可以直接返回,但是不安全。此处返回的是一个实例,调用者可以随意更改(null,clear()等操作)。
    		return Collections.unmodifiableCollection(blockedThreadCollection);
    	}
    
    	@Override
    	public int getBlockedSize() {
    		return blockedThreadCollection.size();
    	}
    }
    
    public class LockTest {
    	public static void main(String[] args) throws InterruptedException {
    		final BooleanLock booleanLock = new BooleanLock();
    		Stream.of("T1", "T2", "T3", "T4").forEach(name -> {
    			new Thread(() -> {
    				try {
    					booleanLock.lock(5000L);
    					Optional.of(Thread.currentThread().getName() + " have the lock Monitor.").ifPresent(System.out::println);
    					work();
    				} catch (InterruptedException e) {
    					e.printStackTrace();
    				} catch (Lock.TimeOutException e) {
    					Optional.of(Thread.currentThread().getName() + " time out.").ifPresent(System.out::println);
    				} finally {
    					booleanLock.unlock();
    				}
    			}, name).start();
    		});
    
    		// 问题:违规非法操作。导致运行混乱
            /*Thread.sleep(100);
            booleanLock.unlock();*/
    	}
    
    	private static void work() throws InterruptedException {
    		Optional.of(Thread.currentThread().getName() + " is working...").ifPresent(System.out::println);
    		Thread.sleep(10_000);
    	}
    }
    
    展开全文
  • Java并发编程——自定义Lock

    千次阅读 2019-03-30 23:56:30
    public interface Lock { class TimeOutException extends Exception { public TimeOutException(String message) { super(message); } } void lock() throws InterruptedException; void lock(...

    一、引言

    在学习JUC并发包的时,会介绍Lock锁。为了更深入的了解Lock锁的机制,我们可以自定义一个Lock锁,这样去读Lock源码可能好理解一点。

    二、自定义Lock锁

    1、定义Lock接口
    
    public interface Lock {
    
    	class TimeOutException extends Exception {
    		public TimeOutException(String message) {
    			super(message);
    		}
    	}
    
    	void lock() throws InterruptedException;
    
    	void lock(long mills) throws InterruptedException, TimeOutException;
    
    	void unlock();
    
    	Collection<Thread> getBlockedThread();
    
    	int getBlockedSize();
    }
    
    2、Lock实现类
    public class BooleanLock implements Lock {
    
    	// 表示对象的锁是否被占用,true表示对象锁已经被占用
    	private boolean initValue;
    
    	// 表示被阻塞线程的集合
    	private Collection<Thread> blockedThreadCollection = new ArrayList<>();
    
    	// 记录获得当前对象锁的线程
    	private Thread currentThread;
    
    	public BooleanLock() {
    		this.initValue = false;
    	}
    
    	/**
    	 * 加锁,使用synchronized实现同步
    	 */
    	@Override
    	public synchronized void lock() throws InterruptedException {
    		// 如果锁已经被占用,则阻塞当前线程
    		while (initValue) {
    			//将线程加入到阻塞线程集合
    			blockedThreadCollection.add(Thread.currentThread());
    			this.wait();
    		}
    
    		// 锁没有被占用,则当前线程获得锁
    		blockedThreadCollection.remove(Thread.currentThread());
    		this.initValue = true;
    		this.currentThread = Thread.currentThread();
    	}
    
    	/**
    	 * 当线程等待一定时间后,没有释放锁,则其他线程抛出超时异常
    	 */
    	@Override
    	public synchronized void lock(long mills) throws InterruptedException, TimeOutException {
    		if (mills <= 0)
    			lock();
    
    		long hasRemaining = mills;
    		long endTime = System.currentTimeMillis() + mills;
    		while (initValue) {
    			if (hasRemaining <= 0)
    				throw new TimeOutException("Time out");
    			blockedThreadCollection.add(Thread.currentThread());
    			this.wait(mills);
    			hasRemaining = endTime - System.currentTimeMillis();
    		}
    
    		this.initValue = true;
    		this.currentThread = Thread.currentThread();
    	}
    
    	/**
    	 * 释放锁
    	 */
    	@Override
    	public synchronized void unlock() {
    		// 只有占用锁对象的线程,才能释放锁。不然main线程释放锁,程序会有问题。
    		if (Thread.currentThread() == currentThread) {
    			this.initValue = false;
    			System.out.println(Thread.currentThread().getName() + " release the lock monitor.");
    			this.notifyAll();
    		}
    	}
    
    	@Override
    	public Collection<Thread> getBlockedThread() {
    		//保证更新集合操作安全,不存在安全问题
    		return Collections.unmodifiableCollection(blockedThreadCollection);
    	}
    
    	@Override
    	public int getBlockedSize() {
    		return blockedThreadCollection.size();
    	}
    }
    
    3、测试
    public class LockTest {
    
    	public static void main(String[] args) throws InterruptedException {
    
    		final BooleanLock booleanLock = new BooleanLock();
    
    		//创建4个线程
    		for (int i = 1; i < 5; i++) {
    
    			new Thread("T" + i) {
    				@Override
    				public void run() {
    					try {
    						booleanLock.lock(10000);
    						System.out.println(Thread.currentThread().getName() + " have the lock Monitor");
    						work();
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					} catch (Lock.TimeOutException e) {
    						System.out.println(Thread.currentThread().getName() + " time out");
    					} finally {
    						booleanLock.unlock();
    					}
    				};
    			}.start();
    		}
    
    	}
    
    	private static void work() throws InterruptedException {
    		System.out.println(Thread.currentThread().getName() + " is Working...");
    		Thread.sleep(40_000);
    	}
    }
    
    4、测试结果

    在这里插入图片描述

    三、小结

    自定义一个Lock锁,熟悉Synchronized的同时,深入理解JUC中的Lock。

    展开全文
  • 自定义Lock

    2019-04-21 16:45:47
    自定义Lock锁 import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.AbstractQueuedSynchronizer; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; ...

    自定义Lock锁

    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.locks.AbstractQueuedSynchronizer;
    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.Lock;
    
    class MyLock implements Lock{
        private Sync sync=new Sync();
        //内部类实现AQS,覆写protected修饰的方法即可
        static class Sync extends AbstractQueuedSynchronizer{
            @Override
            //规定arg=1时表示拿到锁
            protected boolean tryAcquire(int arg) {
                if(arg!=1){
                    throw new RuntimeException("arg不为1!");
                }
                if(compareAndSetState(0,1)){
                    setExclusiveOwnerThread(Thread.currentThread());
                    return true;
                }
                return false;
            }
    
            @Override
            protected boolean tryRelease(int arg) {
                if(arg==0){
                    throw new IllegalMonitorStateException();
                }
                setExclusiveOwnerThread(null);
                setState(0);
                return true;
            }
    
            @Override
            protected boolean isHeldExclusively() {//判断当前线程是否拿到锁
                return getState()==1;
            }
        }
        @Override
        public void lock() {
            sync.acquire(1);
        }
    
        @Override
        public void lockInterruptibly() throws InterruptedException {
            sync.acquireInterruptibly(1);
        }
    
        @Override
        public boolean tryLock() {
            return sync.tryAcquire(1);
        }
    
        @Override
        public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
            return sync.tryAcquireNanos(1,time);
        }
    
        @Override
        public void unlock() {
            sync.release(1);
        }
    
        @Override
        public Condition newCondition() {
            return null;
        }
    }
    class MyThread implements Runnable{
        Lock lock=new MyLock();
        @Override
        public void run() {
            try{
                lock.lock();
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }finally {
                lock.unlock();
            }
        }
    }
    public class Test{
        public static void main(String[] args) {
            MyThread mt=new MyThread();
            for(int i=0;i<10;i++){
                Thread thread=new Thread(mt);
                thread.start();
            }
        }
    }
    
    展开全文
  • 自定义lock

    2019-06-23 17:06:39
    主要方法: lock(加锁) unlock(解除锁) package com.code.constructor.lock; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks...import java.util.concurrent.locks.Lock; public class ...

    主要方法: lock(加锁) unlock(解除锁)

    package com.code.constructor.lock;
    
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.Lock;
    
    public class MyLock implements Lock {
    
        /**
         * 自定义lock
         */
        private boolean isUseLock = false; // 锁状态是否使用中
        private Thread useLock = null; // 使用锁的线程
        private int lockCount = 0;  // 可重入锁的线程使用次数统计
    
        @Override
        public synchronized void lock() {
            Thread nowThread = Thread.currentThread();
            while (isUseLock && nowThread != useLock) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            useLock = nowThread;
            isUseLock = true; // 使用中
            lockCount++;
        }
    
        @Override
        public synchronized void unlock() {
            Thread nowThread = Thread.currentThread();
            if (nowThread == useLock) {
                lockCount--;
                if (lockCount == 0) {
                    isUseLock = false;
                    notifyAll();
                }
            }
    
        }
    
        @Override
        public void lockInterruptibly() throws InterruptedException {
    
        }
    
        @Override
        public boolean tryLock() {
            return false;
        }
    
        @Override
        public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
            return false;
        }
    
        @Override
        public Condition newCondition() {
            return null;
        }
    }
    
    
    展开全文
  • 自定义Lock类、 实现abstractQueuedSynchronizer。
  • 实现自定义Lock

    2018-11-30 07:22:06
    实现自定义Lock类准备工作实现过程工作原理扩展学习更多关注 锁是Java并发API提供的基本同步机制之一,每次只有一个线程可以执行代码块,因此用来保护代码的关键部分。锁机制提供如下两种操作: lock():当访问...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 52,871
精华内容 21,148
关键字:

java自定义lock

java 订阅