2

我有一个两部分的问题...

  1. 我有一个类,其中有一个函数,在给定时间只能由任何一个线程访问。使它成为一个synchronized函数或一个synchronized块仍然允许多个线程,因为不同的线程在类中访问它。如何确保只有一个线程访问此代码?(见下面的代码示例)

  2. 使用同步函数,对该函数的调用会排队。有没有办法只允许最后一次调用函数来访问代码?因此,如果我当前有 Thread1 访问我的函数,则 Thread2 和 Thread3 尝试访问它(按此顺序),一旦 Thread1 完成,将只授予 Thread3 访问权限。

    public void doATask() {
        // I create a new thread so the interface is not blocked
        new Thread(new Runnable() {
    
            @Override
            public void run() {
                doBackgroundTask();
            }
        }).start();
    }
    
    private void doBackgroundTask(MyObject obj) {
        // perform long task here that is only being run by one thread
        // and also only accepts the last queued thread
    }
    

谢谢你的帮助!

4

2 回答 2

2

如果您的示例中的第二个线程可以return,您可以使用锁和跟踪执行该方法的最后一个线程的组合。它可能看起来像这样:

private volatile Thread lastThread;
private final ReentrantLock lock = new ReentrantLock();

private void doBackgroundTask(Object obj) throws InterruptedException {
    Thread currentThread = Thread.currentThread();
    lastThread = currentThread;
    try {
        // wait until lock available
        lock.lockInterruptibly();
        // if a thread has arrived in the meantime, exit and release the lock
        if (lastThread != currentThread) return; 
        // otherwise
        // perform long task here that is only being run by one thread
        // and also only accepts the last queued thread
    } finally {
        lock.unlock();
    }
}

带有额外日志记录的完整工作测试,显示线程交错并且 T2 退出而不做任何事情:

class Test {

    private volatile Thread lastThread;
    private final ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) throws Exception {
        final Test instance  = new Test();
        Runnable r = new Runnable() {

            @Override
            public void run() {
                try {
                    instance.doBackgroundTask(null);
                } catch (InterruptedException ignore) {}
            }
        };
        Thread t1 = new Thread(r, "T1");
        Thread t2 = new Thread(r, "T2");
        Thread t3 = new Thread(r, "T3");
        t1.start();
        Thread.sleep(100);
        t2.start();
        Thread.sleep(100);
        t3.start();
    }

    private void doBackgroundTask(Object obj) throws InterruptedException {
        Thread currentThread = Thread.currentThread();
        System.out.println("[" + currentThread.getName() + "] entering");
        lastThread = currentThread;
        try {
            // wait until lock available
            lock.lockInterruptibly();
            // if a thread has arrived in the meantime, exit and release the lock
            if (lastThread != currentThread) return;
            // otherwise
            // perform long task here that is only being run by one thread
            // and also only accepts the last queued thread
            System.out.println("[" + currentThread.getName() + "] Thinking deeply");
            Thread.sleep(1000);
            System.out.println("[" + currentThread.getName() + "] I'm done");
        } finally {
            lock.unlock();
            System.out.println("[" + currentThread.getName() + "] exiting");
        }
    }
}

输出:

[T1] entering
[T1] Thinking deeply
[T2] entering
[T3] entering
[T1] I'm done
[T1] exiting
[T2] exiting
[T3] Thinking deeply
[T3] I'm done
[T3] exiting
于 2013-03-28T02:49:21.020 回答
2

你想要的可能是一个等待信号做一些工作的工作线程。doATask()只需发送一个信号即可触发工作。累积信号相当于一个信号。

final Object lock = new Object();
MyObject param = null;

public void doATask(arg) 
    synchronized(lock)
        param=arg;
        lock.notify();

MyObject awaitTask()
    synchronized(lock)
        while(param==null)
            lock.wait();
        tmp=param;
        param=null;
        return tmp;

// worker thread

public void run()
    while(true)
        arg = awaitTask();
        doBackgroundTask(arg);
于 2013-03-28T03:05:10.187 回答