简体   繁体   English

如何在 java 中不使用 wait() 或 sleep() 使线程等待

[英]How to make a thread wait without using wait() nor sleep() in java

I am writing a class called MyReentrantLock and I have to create a function called acquire() that locks a thread if it's not locked and if it is indeed locked then it has to wait until it unlocks to lock it again.我正在编写一个名为 MyReentrantLock 的 class,我必须创建一个名为 acquire() 的 function,如果线程未锁定并且确实已锁定,则它必须等到它解锁才能再次锁定它。 It's kind of confusing and I can't use wait() or sleep(), only AtomicBoolean and Thread class in java.这有点令人困惑,我不能使用 wait() 或 sleep(),只能使用 AtomicBoolean 和 Thread class in java。

public class MyReentrantLock implements Lock{

    AtomicBoolean locked = new AtomicBoolean(false);
    long IdOfThreadCurrentlyHoldingLock;
    @Override
    public void acquire() {

        if(!locked.compareAndSet(false,true)){
           WHAT DO I WRITE HERE!!
        }

        locked.compareAndSet(false, true);
        IdOfThreadCurrentlyHoldingLock=Thread.currentThread().getId();

    }


    @Override
    public boolean tryAcquire() {
        if(!locked.compareAndSet(false,true))
            return false;
        else {
            acquire();
            return true;
        }
    }

    @Override
    public void release() {
       locked.compareAndSet(true,false);
       if(!locked.compareAndSet(true,false) || IdOfThreadCurrentlyHoldingLock!=Thread.currentThread().getId()){
           throw new IllegalReleaseAttempt();
       }

    }

Replace your if with a while .while替换你的if You may keep the body empty, even though it might be advisable to sleep some milliseconds.你可以让身体保持空虚,即使睡眠几毫秒可能是明智的。

The reason is: Your method acquire neither throws an exception nor does it return a result (success/failure).原因是:您的方法 acquire 既不抛出异常也不返回结果(成功/失败)。 Thus the calling code would assume when the call to acquire is done, the thread can continue doing the sensitive job.因此,调用代码会假定,当对 acquire 的调用完成时,线程可以继续执行敏感工作。

So you cannot exit the method without having the lock, even if that means to wait indefinitely.所以你不能在没有锁的情况下退出方法,即使这意味着无限期地等待。 A more advanced method would allow to define a timeout but then also needs to communicate whether the lock is aquired or the timeout was reached.一种更高级的方法将允许定义超时,但随后还需要传达是否已获取锁或已达到超时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM