我在Java中实现了Producer-Consumer问题,我希望生产者线程在特定的时间内运行,例如1天,将对象放在BlockingQueue
特定的推文中,通过Twitter4j-从Twitter Streaming API流式传输,消费者线程从队列中使用这些对象并将它们写入文件。我使用了来自Read the 30Million user id's one by one from the big file的PC逻辑,其中producer是FileTask,而consumer是CPUTask(检查第一个答案;我的方法使用相同的迭代/ try-catch blocks
)。当然,我相应地调整了实现。
我的主要职责是:
public static void main(String[] args) {
....
final int threadCount = 2;
// BlockingQueue with a capacity of 200
BlockingQueue<Tweet> tweets = new ArrayBlockingQueue<>(200);
// create thread pool with given size
ExecutorService service = Executors.newFixedThreadPool(threadCount);
Future<?> f = service.submit(new GathererTask(tweets));
try {
f.get(1,TimeUnit.MINUTES); // Give specific time to the GathererTask
} catch (InterruptedException | ExecutionException | TimeoutException e) {
f.cancel(true); // Stop the Gatherer
}
try {
service.submit(new FileTask(tweets)).get(); // Wait til FileTask completes
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
service.shutdownNow();
try {
service.awaitTermination(7, TimeUnit.DAYS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
现在,问题在于,虽然它确实对推文进行流式处理并将它们写入文件,但它永远不会终止,也永远不会到达f.cancel(true)
部分。我应该改变它才能正常工作?另外,你能在答案中解释一下线程逻辑出了什么问题,所以我从错误中学到了什么?提前谢谢。
这些是我的PC类的run()
函数:
制片:
@Override
public void run() {
StatusListener listener = new StatusListener(){
public void onStatus(Status status) {
try {
tweets.put(new Tweet(status.getText(),status.getCreatedAt(),status.getUser().getName(),status.getHashtagEntities()));
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentTread.interrupt(); // Also tried this command
}
}
public void onException(Exception ex) {
ex.printStackTrace();
}
};
twitterStream.addListener(listener);
... // More Twitter4j commands
}
消费者:
public void run() {
Tweet tweet;
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("out.csv", true)))) {
while(true) {
try {
// block if the queue is empty
tweet = tweets.take();
writeTweetToFile(tweet,out);
} catch (InterruptedException ex) {
break; // GathererTask has completed
}
}
// poll() returns null if the queue is empty
while((tweet = tweets.poll()) != null) {
writeTweetToFile(tweet,out);
}
} catch (IOException e) {
e.printStackTrace();
}
}