关于创建同步机制

时间:2012-12-09 05:03:49

标签: java multithreading

  

可能重复:
  Testing a multithreaded Java class that runs the threads sequentially

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

我开发了一个类,让多个线程按顺序运行,一次一个,按顺序运行。此类的claimAccess函数和发布Access函数之间的所有应用程序代码将一次仅在一个线程中执行。所有其他线程将在队列中等待,直到前一个线程完成。请建议我想通过在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[])
{

}

请告诉我如何在我的主要方法中生成thr线程来测试上面的类.. !!请指教

2 个答案:

答案 0 :(得分:1)

这应该让你开始......

public static void main (String args[])
{
    AccessGate gate = new AccessGate();

    // create as many threads as you like
    Thread t1 = new MyThread(gate);
    Thread t2 = new MyThread(gate);

    // start all the threads you created
    t1.start();
    t2.start();        
}

class MyThread extends Thread {

    AccessGate gate;

    public MyThread(AccessGate g) {
        gate = g;
    }

    public void run() {
        gate.claimAccess();
        // Do something or print something.
        // Could output several statements.
        // Why not do a sleep as well to see if other threads interrupt
        // this code section.
        gate.releaseAccess();
    }
}

答案 1 :(得分:0)

考虑使用Executors.newSingleThreadExecutor()。这是一个只有一个线程执行任务的线程池。只有在第一个任务完成后,下一个任务才会开始执行:

Executor executor = Executors.newSingleThreadExecutor();
Future<String> future1 = executor.submit(new Callable<String>() {
    @Override
    String call() throws Exception {
        // my first task
    }
});
Future<String> future2 = executor.submit(new Callable<String>() {
    @Override
    String call() throws Exception {
        // my second task
    }
});
...

您可以通过Future API检索任务执行结果,还可以跟踪每个作业的状态。