java 实现等待异步线程多久超时返回的功能

实现类

public class AutoResetEvent {
    private final Object a = new Object();
    //是否激活线程,true:是  false:否
    private volatile boolean b = false;

    public AutoResetEvent(boolean open) {
        this.b = open;
    }

    public void a() throws InterruptedException {
        synchronized(this.a) {
            while(!this.b) {
                this.a.wait();
            }

            this.b = false;
        }
    }

    public boolean a(long timeout) throws InterruptedException {
        boolean isSuc = false;
        synchronized(this.a) {
            long t = System.currentTimeMillis();

            while(!this.b) {
                this.a.wait(timeout);
                isSuc = true;
                if (System.currentTimeMillis() - t >= timeout) {
                    isSuc = false;
                    break;
                }
            }

            this.b = false;
            return isSuc;
        }
    }

    public void b() {
        synchronized(this.a) {
            this.b = true;
            this.a.notify();
        }
    }

    public void c() {
        this.b = false;
    }
}

使用

try {
            this.b = new AutoResetEvent(false);
            (new SocketConnectThread()).start();
            this.b.a(5000L);
        } catch (InterruptedException var6) {
            var6.printStackTrace();
        } finally {
            this.b = null;
        }

版权声明:本文为qq_40351360原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。