Java并发编程(自定义同步组件)

来源:互联网 发布:匿名聊天源码 编辑:程序博客网 时间:2024/06/05 12:41

并发包结构图:
这里写图片描述

编写一个自定义同步组件来加深对同步器的理解

业务要求:
* 编写一个自定义同步组件来加深对同步器的理解。
* 设计一个同步工具:该工具在同一时刻,只允许至多两个线程同时访问,超过两个线程的
* 访问将被阻塞,我们将这个同步工具命名为TwinsLock。
* 首先,确定访问模式。TwinsLock能够在同一时刻支持多个线程的访问,这显然是共享式
* 访问,因此,需要使用同步器提供的acquireShared(int args)方法等和Shared相关的方法,这就要
* 求TwinsLock必须重写tryAcquireShared(int args)方法和tryReleaseShared(int args)方法,这样才能
* 保证同步器的共享式同步状态的获取与释放方法得以执行。
* 其次,定义资源数。TwinsLock在同一时刻允许至多两个线程的同时访问,表明同步资源
* 数为2,这样可以设置初始状态status为2,当一个线程进行获取,status减1,该线程释放,则
* status加1,状态的合法范围为0、1和2,其中0表示当前已经有两个线程获取了同步资源,此时
* 再有其他线程对同步状态进行获取,该线程只能被阻塞。在同步状态变更时,需要使用
* compareAndSet(int expect,int update)方法做原子性保障。
* 最后,组合自定义同步器。前面的章节提到,自定义同步组件通过组合自定义同步器来完
* 成同步功能,一般情况下自定义同步器会被定义为自定义同步组件的内部类

import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.AbstractQueuedSynchronizer;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;public class TwinsLock implements Lock {    private final  Sync sync = new Sync(2);    private static final class  Sync extends AbstractQueuedSynchronizer {        Sync(int count) {            if(count <= 0) {                throw  new IllegalArgumentException("count must large zero!");            }            setState(count);        }        //共享式同步状态的获取。        public int tryAcquireShared(int reduceCount) {            for(;;) { //自旋                int current = getState();                int newCount = current - reduceCount;                if(newCount < 0 || compareAndSetState(current, newCount)) {                    return newCount;                }            }        }        //共享式同步状态释放.        public boolean tryReleaseShared(int returnCount) {            for(;;) {//自旋.                int current = getState();                int newCount = current + returnCount;                if(compareAndSetState(current, newCount)) {                    return true;                }            }        }        final ConditionObject newCondition() {            return new ConditionObject();        }    }    //共享式获取    public void lock() {        sync.acquireShared(1);    }    public void lockInterruptibly() throws InterruptedException {        //和acquire方法相同, 但是该方法响应中段.        sync.acquireInterruptibly(1);    }    //如果返回大于等于0表示获取成功。    public boolean tryLock() {        return sync.tryAcquireShared(1) >= 0;    }    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {        return sync.tryAcquireSharedNanos(1, unit.toNanos(time));    }    //释放所资源    public void unlock() {        sync.releaseShared(1);    }    public Condition newCondition() {        return sync.newCondition();    }}
import javafx.concurrent.Worker;import java.util.concurrent.locks.Lock;public class TwinsLockTest {    public  static  void main(String argc[]){        final Lock lock = new TwinsLock();        class Worker extends Thread{            public void run() {                while(true) {                    lock.lock();                    try {                            System.out.println(Thread.currentThread().getName());                            Thread.sleep(1500);                    } catch (InterruptedException e) {                       System.out.println("interruptException!");                    }                    finally {                        lock.unlock();                        break;                    }                }            }        }        for(int i = 0; i < 10; i++) {            Worker worker = new Worker();            //worker.setDaemon(true);            worker.start();        }        //每间隔一秒钟打印一个空行.        for(int i = 0; i <10; i++) {            try {                Thread.sleep(1000);            } catch (InterruptedException e) {                e.printStackTrace();            }            System.out.println();        }    }}

AbstractQueuedSynchronizer的介绍和原理分析
参考博客

原创粉丝点击