我需要独立执行2个任务。

第一个任务

每分钟一次,应检查特定文件夹中是否有文件。如果存在,则应将文件名添加到队列中。

可以按照以下步骤进行操作:

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class schedulerExample extends Thread{

    public void checkFile()
    {
        System.out.println("checking whether file exist in folder");

    }

    public void getFiles()
    {
        System.out.println("getting the file names");
    }

    public void enqueueFiles()
    {
        System.out.println("add files to queue");
    }
    public static void main(String[] args) {

    final schedulerExample obj = new schedulerExample();
    ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1);
    executor.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {

            obj.checkFile();
            obj.getFiles();
            obj.enqueueFiles();

        }
    }, 0, 1, TimeUnit.MINUTES);


    }

}

第二个任务

如果队列为空,请 hibernate 一分钟,否则将逐一处理队列中的文件。
public class processModel extends Thread{

    public static void getQueueSize(int size)
    {
        System.out.println("getting queue size");

    }
    public void dequeue()
    {

        // dequeue the queue
        System.out.println("dequeue");

    }

    public void processFile()
    {
        // process the file
        System.out.println("process file");
    }

    public static void main(String[] args) {
        final boolean flag = true;
        final int size = 9;
        final processModel obj = new processModel();
        Thread t1 = new Thread(){
            public void run()
            {
                while(flag)
                {
                obj.dequeue();
                obj.processFile();
                getQueueSize(size);
                    if(size == 0)
                    {
                        try
                        {
                        Thread.sleep(60000);
                        }
                        catch(InterruptedException e)
                        {

                        }
                    }
                }

            }

        };

        t1.start();

    }

}

现在,我需要在一个类中同时进行这两个操作。那可能吗?

一个线程应该每分钟获取一次文件。另一个线程应一个接一个地执行文件..如果没有文件,则等待一分钟,然后再次检查。在第二种方法中,我使用了无限循环-而不是,有没有一种方法可以使我一个接一个地执行事情?

最佳答案

从队列对象获取文件或向队列对象添加文件时,对队列对象进行同步。

在读取的线程中,如果队列为空,则调用wait()
在检查新文件的线程中,将新文件添加到队列后,调用notify()

通常是这样的。

您还应该防止将正在处理的文件添加到队列中。

10-04 11:33
查看更多