简体   繁体   English

用Java锁定对象

[英]Lock an object in Java

How can a Java object be locked for a certain amount of time (eg 20 seconds)? 如何将Java对象锁定一定时间(例如20秒)? By locked, I mean that the object cannot be accessed in that time. 通过锁定,我的意思是那个时间不能访问该对象。

You could synchronize all of the methods, and have a lock method that just waits for 20 seconds and returns. 您可以同步所有方法,并拥有一个等待20秒然后返回的lock方法。

 public  synchronized void lock(){
            try {
                Thread.sleep(20 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt();
            }
        }

Remember the synchronize all of the methods, and keep all fields private. 记住同步所有方法,并使所有字段保持私有。 (Everything on the interface should be synchronized ) (接口上的所有内容都应该synchronized

If you need to do this for a general object - ie, one you can't write or specify yourself - then it's time to learn how Monads work: 如果您需要对一个通用对象(即您无法编写或指定自己的对象)执行此操作,那么该学习一下Monads如何工作的时候了:

public class Lockable<T> {

    private T _t;
    public Lockable(T t){
        _t = t;
    }

    public synchronized void perform(Consumer<T> consumer){
        consumer.accept(_t);
    }

    public synchronized <R> R get(Function<T, R> function){
        return function.apply(_t);
    }

    public synchronized<R> Lockable<R> map(Function<T, R> function){
        return new Lockable(function.apply(_t));
    }

    public synchronized void lock(){
        try {
            Thread.sleep(20 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread.interrupt();
        }
    }

}

The above isn't 100% unbeatable, but so long as you'd don't let un-wrapped references loose, it should be okay. 上面的内容并不是100%无与伦比的,但是只要您不要让未包装的引用松散,就可以了。

There is no general mechanism to lock objects in Java. 没有通用的机制来锁定Java中的对象。

You can define your own class of lockable objects (eg, as suggested by David Pérez Cabrera and Edward Peters), but there is no way to lock arbitrary objects that weren't designed to be lockable. 您可以定义自己的可锁定对象类(例如,DavidPérezCabrera和Edward Peters的建议),但是无法锁定非设计为可锁定的任意对象。

To be more precise, all of its method must be synchronized and all of its field must be private . 更精确地说,它的所有方法都必须synchronized并且它的所有字段都必须是private

public class LockeableObject {

    private String fieldFoo;

    public synchronized void lock() throws InterruptedException{
        this.wait(20 * 1000); // 20 seconds
    }

    public synchronized void foo() {
         ...
    }

    public synchronized void foo2() {
         ...
    }

}

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

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