前言为什么要用java来实现?因为php是一门不完整的语言!因为对于并发,最重要的是原子操作。其中,并发和阻塞基本都是通过硬件的方式来实现的。信号量基本上是每个操作系统都提供的API。什么是读写锁?其实读写锁有两种。一个是先读,另一个是先写。什么是信号量信号量最重要的就是P操作和V操作。P操作信号量减1。当信号量小于0时,此时线程阻塞。V操作信号量会加1。如果小于等于0,唤醒一个等待线程。实现互斥锁。互斥意味着一次只能运行一个线程。设置信号量初始值为1,当信号量执行获取锁时,信号量减1。信号量为0,下一个线程要获取锁时,信号量减1。此时次,当信号量小于0时,线程被阻塞。当锁被释放时,信号量会加1。并唤醒一个等待线程。publicclassMutexLock{privateSemaphoremutex=newSemaphore(1);publicvoidlock()throwsInterruptedException{mutex.acquire();}publicvoidunlock(){mutex.release();ReadLock和WriteLock都加了写锁。这样可以确保只有一个线程可以同时执行读取或写入操作。读写锁允许重复读取。所以添加一个readCound计数。指示当前存在多少读取线程。因为readCount是共享变量。所以使用countMutex进行保护。当readCount等于0时,表示第一个读线程。尝试获取锁。如果你得到一个写锁,readCount++。下一个读取线程不需要获取锁。如果没有获取到锁,readCount永远为0,reader线程处于等待状态。离开时,只有在所有读取完成后才会释放锁。唤醒一个等待的线程。一般写线程。具体实现publicclassReadWriteLock{privateintreadCount=0;privateMutexLockcountMutex=newMutexLock();privateMutexLockwriteMutex=newMutexLock();publicclassReadLock{publicvoidlock()throwsInterruptedException{//readCount是一个共享变量,所以需要实现一个锁来控制读写//synchronized(ReadWriteLock.class){}countMutex.lock();//只有第一个读者才会锁定写锁。其他读者进行下一步if(readCount==0){writeMutex.lock();}++读数;countMutex.unlock();}publicvoidunlock()throwsInterruptedException{countMutex.lock();读取计数--;//只有当读者读完了,才会执行写操作if(readCount==0){writeMutex.unlock();}countMutex.unlock();}}publicclassWriteLock{publicvoidlock()throwsInterruptedException{writeMutex.lock();}publicvoidunlock(){writeMutex.unlock();}}}测试代码publicclassMain{privatestaticReadWriteLockreadWriteLock=newReadWriteLock();privatestaticReadWriteLock.ReadLockreadLock=readWriteLock.newReadLock();私有静态ReadWriteLock.WriteLockwriteLock=readWriteLock.newWriteLock();p公共静态无效主要(字符串[]args){测试();}privatestaticvoidtest(){线程t;intwriteNum=(int)(Math.random()*10);for(inti=0;i<10;i++){//if(i==writeNum){if((int)(Math.random()*10)>5){t=newThread(){publicvoidrun(){try{writeLock.lock();System.out.println(this.getName()+"写作");Thread.sleep((int)(Math.random()*6*1000));System.out.println(this.getName()+"写入完成");writeLock.unlock();}catch(异常e){}}};}else{t=newThread(){publicvoidrun(){尝试{readLock.lock();System.out.println(this.getName()+"阅读");Thread.sleep((int)(Math.random()*3*1000));System.out.println(this.getName()+"读取完成");readLock.unlock();}catch(异常e){}}};}t.setName("线程"+i);t.开始();}}}结果图片上传不了,直接贴上来某次测试结果如下thread2writingthread2writedonethread4writingthread4writedonethread9writingthread9writedonethread0readingthread6readingthread8readingthread7readingthread5readingthread0readdonethread6readdonethread5readdonethread8readdonethread7readdonethread3writingthread3writedonethread1writingthread1写完成
