重複の可能性:
スレッドを順番に実行するマルチスレッドJavaクラスのテスト
以下の質問を重複したものとして扱わないでください。
マルチスレッドを一度に1つずつ順番に順番に実行できるクラスを開発しました。このクラスのclaimAccess関数とreleaseAccess関数の間のすべてのアプリケーションコードは、一度に1つのスレッドでのみ実行されます。他のすべてのスレッドは、前のスレッドが完了するまでキューで待機します。main()メソッド自体にコードを記述して、クラスをテストすることをお勧めします。
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();
}
}
}
}
今私の主な方法は..
public static void main (String args[])
{
}
上記のクラスをテストするために、メインメソッドでスレッドを生成する方法を教えてください..!!アドバイスしてください