zoukankan      html  css  js  c++  java
  • 使用synchronized写一个显示锁

    public interface MyLock {
        
        void lock () throws InterruptedException;
        
        void lock(long millis) throws TimeoutException , InterruptedException ,ParametersIllegalException;
        
        void unlock();
        
        class TimeoutException  extends Exception{
            
            TimeoutException(String msg){
                super(msg);
            }
            private static final long serialVersionUID = 1L;
        }
        
        class ParametersIllegalException  extends Exception{
            
            ParametersIllegalException(String msg){
                super(msg);
            }
            private static final long serialVersionUID = 1L;
        }
    }
    public class MyLockImpl  implements MyLock{
    
        private boolean  initValue; // false表示monitor没有被占用
        
        private Thread currentThread;
        
        @Override
        public  synchronized void lock() throws InterruptedException {
            while(initValue) {//monitor被占用
                this.wait();
            }
            initValue = true;
            currentThread = Thread.currentThread();
        }
    
        @Override
        public synchronized void unlock() {
            if(currentThread == Thread.currentThread()) {
                System.out.println(""+Thread.currentThread().getName()+"" + " release the monitor");
                initValue = false;
                this.notifyAll();
            }
        }
    
        @Override
        public  synchronized void lock(long millis) throws TimeoutException, InterruptedException, ParametersIllegalException {
                if (millis <= 0) 
                   throw new ParametersIllegalException("parameters illegal");
                long hasRemaining = millis;
                long endTime = System.currentTimeMillis() + millis;
                while (initValue) {
                    if (hasRemaining <= 0)
                        throw new TimeoutException("Time out");
                    this.wait(millis);
                    hasRemaining = endTime - System.currentTimeMillis();
                }
                this.initValue = true;
                this.currentThread = Thread.currentThread();
        }
        
    
    }
    public class MyLockTest {
        
        public static void main(String[] args) {
            MyLock myLock = new MyLockImpl();
            
            Stream.of("T1","T2","T3","T4").forEach(name -> 
                new Thread(()-> {
                    try {
                        myLock.lock(10);
                        System.out.println(""+Thread.currentThread().getName()+"" +" get the monitor");
                        m1();
                    } catch (InterruptedException  e) {
                        e.printStackTrace();
                    } catch (TimeoutException e) {
                        System.out.println(""+Thread.currentThread().getName()+"" +" timeout");
                    } catch (ParametersIllegalException e) {
                        System.out.println(""+Thread.currentThread().getName()+"" +" parameter illegal");
                        //e.printStackTrace();
                    }finally {
                        myLock.unlock();
                    }
                },name).start()
            );
        }
        
        
        public static void m1() throws InterruptedException {
            System.out.println(""+Thread.currentThread().getName()+"" + "is working ...");
            Thread.sleep(3_000);
        }
    
    }

    注意wait方法可能存在spurious(假的)唤醒,wait方法应该在一个循环中使用

  • 相关阅读:
    warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
    Windows10+CLion+OpenCV4.5.2开发环境搭建
    Android解决部分机型WebView播放视频全屏按钮灰色无法点击、点击全屏白屏无法播放等问题
    MediaCodec.configure Picture Width(1080) or Height(2163) invalid, should N*2
    tesseract
    Caer -- a friendly API wrapper for OpenCV
    Integrating OpenCV python tool into one SKlearn MNIST example for supporting prediction
    Integrating Hub with one sklearn mnist example
    What is WSGI (Web Server Gateway Interface)?
    Hub --- 机器学习燃料(数据)的仓库
  • 原文地址:https://www.cnblogs.com/moris5013/p/10716847.html
Copyright © 2011-2022 走看看