正确等待获取线程队列

时间:2014-05-23 13:28:49

标签: java multithreading queue

好的,所以,我有一个java类,其中每个方法都必须在一个线程中运行。 每次和特定时间只执行一个线程。 我已经像这样实现了一个扩展Thread的内部类。

private class MyOperation extends Thread {

    public static final String M1 = "method1";
    public static final String M2 = "method2";
    public static final String M3 = "method3";

    protected long scheduledStartTime = 0;
    private String type;

    public MyOperation(String type, long milliSecondsToWait) {
        this.type = type;
        scheduledStartTime = System.currentTimeMillis() + mlliSecondsToWait;
    }
    @Override
    public void run() {
        switch(type){
        case M1:
            doMethod1();
            break;
        case M2:
            doMethod3();
            break;
        case M3:
            doMethod3();
            break;

        }
        setCurrentOperation(null);
    }
}



private void setCurrentOperation(MyOperation task) {
        synchronized (currentOperation) {
            this.currentOperation = task;
        }
    }

然后我有Thread队列和当前运行的线程

private MyOperation currentOperation;
private Queue <MyOperation> operationList;

我正在提取这样的任务:

    private void fetchTasks() {
    new Thread() {
        @Override
        public void run() {
            while(true) {
                if(currentOperation == null && !operationList.isEmpty()) {
                    currentOperation = getOperation();
                    while(currentOperation.scheduledStartTime > System.currentTimeMillis()) {
                        // do nothing, wait for proper time;
                    }
                    currentOperation.start();
                }
            }
        }

    }.start();
}
    private MyOperation getOperation() {
    synchronized (operationList) {
        return operationList.remove();
    }
}

我正在将线程添加到队列中,例如:

addOperation(new MyOperation(M1, 5));

    private void addOperation(MyOperation task) {
    synchronized (operationList) {
        operationList.add(task);
    }
}

我的问题是:

有没有更好的方法在不同的线程中运行每个方法?

这种获取线程队列的方式是否正确?

非常感谢

2 个答案:

答案 0 :(得分:0)

只是一件小事:如果您的operationsList为空或currentOperation不为空,那么您的主题就会以非常快的速度开始。 您可以使用Thread.wait().notify()来避免这种情况。

此外,您在使用currentOperation时使用synchronized。这可能会让你陷入麻烦。

答案 1 :(得分:0)

您是否考虑过使用ScheduledExecutorService(java.util.concurrent)来安排任务?