【发布时间】:2013-09-13 17:31:56
【问题描述】:
我有一个由 4 个进程组成的程序,所有这些进程都需要一个接一个地运行。
草图是这样的:
第一个进程 - 在多线程中 - 完成他的工作提供数据输入
第二个进程 - 在多线程中 - 完成他的工作提供了一些数据
第三个进程 - 在多线程中 - 完成他的工作提供了一些数据
第四个进程 - 在多线程中 - 完成工作提供数据输出
注意为了让一个进程开始他之前的一个进程需要完成!
在代码草图中看起来像这样:
public class MainClass{
public static void main(){
addThreadPool();
}
public static void addThreadPool(){
ScheduledThreadPoolExecutor eventPool = new ScheduledThreadPoolExecutor(5);
eventPool.sheduleAtFixedRate(new FirstProcess(),0,5, TimeUnits.SECONDS);
eventPool.sheduleAtFixedRate(new SecondProcess(),5,10, TimeUnits.SECONDS);
eventPool.sheduleAtFixedRate(new ThirdProcess(),15,20, TimeUnits.SECONDS);
eventPool.sheduleAtFixedRate(new ForthProcess(),20,25, TimeUnits.SECONDS);
try{
Thread.sleep(20000);
}
catch(InterruptedException e){
System.err.println(e.getMessaage());
}
}
static class FirstProcess implements Runnable {
ReentrantLock lock = new ReentrantLock();
public void run(){
lock.lock();
System.out.println("FirstProcess started/finished");
lock.unlock();
}
}
static class SecondProcess implements Runnable {
ReentrantLock lock = new ReentrantLock();
public void run(){
lock.lock();
System.out.println("SecondProcess started/finished");
lock.unlock();
}
}
static class ThirdProcess implements Runnable {
ReentrantLock lock = new ReentrantLock();
public void run(){
lock.lock();
System.out.println("ThirdProcess started/finished");
lock.unlock();
}
}
static class ForthProcess implements Runnable {
ReentrantLock lock = new ReentrantLock();
public void run(){
lock.lock();
System.out.println("ForthProcess started/finished");
lock.unlock();
}
}
我希望有人回答这是简单的多线程问题。
请使用 ScheduledThreadPoolExecutor 提供帮助!
【问题讨论】:
-
为什么必须将它们作为四个独立的可运行文件?只需将它们捆绑在一个可运行文件中并调用它。
-
如果它们必须按顺序运行,那么使用 4 个不同的线程有什么意义?看来你错过了线程的重点。
标签: java multithreading threadpool