請不要把下面的問題看作是重複的問題..!關於同步的不同方法
我開發了一個讓多線程按順序依次運行的類。這個類的claimAccess函數和release Access函數之間的所有應用程序代碼一次只能在一個線程中執行。所有其他線程將在隊列中等待,直到前一個線程完成。現在請告知可以同樣的事情由像執行人,循環障礙或倒計時鎖也有一些其他的方式來實現.. !!請建議如何能夠通過其他途徑建立
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();
}
}
}
}
排序的任務很重要嗎? –
@NarendraPathai是啊必須維護訂單 – user1881169
'Executors.newSingleThreadExecutor()'呢? –