请不要将以下问题视为重复问题..!
我开发了一个类,可以让多线程按顺序一次运行一个。该类的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/