java - 关于不同的同步方法

标签 java multithreading executors

请不要将以下问题视为重复问题..!

我开发了一个类,可以让多线程按顺序一次运行一个。该类的claimAccess函数和releaseAccess函数之间的所有应用程序代码一次只会在一个线程中执行。所有其他线程将在队列中等待,直到前一个线程完成。现在请建议是否可以通过其他方式(例如执行器、循环屏障或倒计时锁存器)来实现同样的事情..!!请建议如何通过其他方法构建它

import java.util.ArrayList;
import java.util.List;

public class AccessGate {
    protected boolean shouldWait = false;
    protected final List waitThreadQueue = new ArrayList();

    /**
     * For a thread to determine if it should wait. It it is, the thread will
     * wait until notified.
     * 
     */
    public void claimAccess() {
        final Thread thread = getWaitThread();
        if (thread != null) {
            // let the thread wait untill notified
            synchronized (thread) {
                try {
                    thread.wait();
                } catch (InterruptedException exp) {
                }
            }
        }
    }

    /**
     * For a thread to determine if it should wait. It it is, the thread will be
     * put into the waitThreadQueue to wait.
     * 
     */
    private synchronized Thread getWaitThread() {
        Thread thread = null;
        if (shouldWait || !waitThreadQueue.isEmpty()) {
            thread = Thread.currentThread();
            waitThreadQueue.add(thread);
        }
        shouldWait = true;
        return thread;
    }

    /**
     * Release the thread in the first position of the waitThreadQueue.
     * 
     */
    public synchronized void releaseAccess() {
        if (waitThreadQueue.isEmpty()) {
            shouldWait = false;
        } else {
            shouldWait = true;
            // give the claimAccess function a little time to complete
            try {
                Thread.sleep(10);
            } catch (InterruptedException exp) {
            }

            // release the waiting thread
            final Thread thread = (Thread) waitThreadQueue.remove(0);
            synchronized (thread) {
                thread.notifyAll();
            }
        }
    }
}

最佳答案

这是通过ExecutorService

Executors.singleThreadExecutor()将一次执行一个任务并按顺序执行。

Creates an Executor that uses a single worker thread operating off an unbounded queue. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.) Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time.

关于java - 关于不同的同步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13786025/

相关文章:

java - 无法识别 @ContextConfiguration 的参数类

java - 从 TextView 中进行字符串标记

multithreading - SVN 结帐可以是多线程的吗?

java - linux top 显示 java 线程?

java - 使用执行器框架还是普通线程?

amazon-web-services - AWS lambda 中的执行器服务

java - 使用通信层在客户端和服务器之间进行通信

java - 从文件数据中提取特定段落的最佳方法

multithreading - golang写文件阻塞了很多goroutine,为什么不创建很多线程?

java - 使用 ScheduledExecutorService 时在哪里对计划任务执行最终清理