我需要创建两个线程,一个调用调度程序执行器服务,另一个在无限循环中运行以获取和处理文件。
我使用以下代码:
ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1);
executor.scheduleAtFixedRate(new Runnable() {
public void run()
{
obj.checkFileExist();
obj.enqueue();
}
}, 0, 1, TimeUnit.MINUTES);
在一个无限循环中,我一个一个地处理文件:
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);
}
}
};
t1.start();
}
}
我怎样才能同时实现这两个目标?
- 线程 1 - 检查文件夹中是否存在文件。如果是,则将其入队,否则会 hibernate 一分钟.. - 调度程序可以执行此操作
- 线程 2 - 如果队列不为空,则逐一处理。否则睡一分钟
如何同时运行这 2 个线程。如果您显示一些代码,那将对我有很大帮助。
最佳答案
使用两个线程没有任何意义。两个线程同时运行的唯一时间是入队器拾取文件的速度快于出队器处理文件的速度。如果你有一个单一的重复任务,你的解决方案会更简单、更健壮,这将确保你永远不会让一个线程临界地总是领先于另一个(并且代码要简单得多)
ScheduledExecutorService executor = new SingleScheduledThreadPool();
executor.scheduleAtFixedRate(new Runnable() {
public void run() {
for(File file: obj.getCHangedFiles())
obj.processFile(file);
}
}, 0, 1, TimeUnit.MINUTES);
关于java并发与scheduledexecutor和无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12986779/