1

我已经为 twitter 实现了一个 Steaming API。我得到了完美的溪流。但是,我的程序永远不会结束。我尝试了很多组合,但不知道为什么。我在 java 中起诉 Apache AsyncHttpClient。我的目标是启动流,例如 10 秒,获取流,然后优雅地关闭流并退出应用程序(我希望当我的 Main 方法自然结束时会发生这种情况)。这是下面的代码:

public static void main(String[] args) throws Exception
{
    TwitterStreamingHttpClient client = new TwitterStreamingHttpClient();
    Executor ex = Executors.newSingleThreadExecutor();
    ex.execute(client);

    Thread.sleep(5000);
    client.ceaseStream();

    LOG.debug("Keeps running");     
}

和这个:


public class TwitterStreamingHttpClient extends DefaultHttpAsyncClient implements Runnable
{
    private final static Logger LOG = LoggerFactory.getLogger(TwitterStreamingHttpClient.class);
    /**
     * @throws IOReactorException
     */
    public TwitterStreamingHttpClient() throws IOReactorException
    {
        super();
        // TODO: parametrize it, load from config file, spring config file?
        this.getCredentialsProvider().setCredentials(new AuthScope("stream.twitter.com", 80),
                new UsernamePasswordCredentials("username", "password"));
        this.start();
    }
    public void initiateStream() throws UnsupportedEncodingException, InterruptedException, ExecutionException
    {
String requestContent = new String();
requestContent = "track=NothingFeelsBetterThan"; Future future = this.execute(HttpAsyncMethods.createPost( "https://stream.twitter.com/1.1/statuses/filter.json", requestContent, ContentType.APPLICATION_FORM_URLENCODED), new TwitConsumer(), null); Boolean result = future.get(); if(result==null) { LOG.error("Requested to close stream!"); return; } } public void ceaseStream() { try { this.shutdown(); LOG.info("Shutting down the stream"); } catch (InterruptedException e) { LOG.debug("InterruptedException {}", e); } }

/*
 * (non-Javadoc)
 * 
 * @see java.lang.Runnable#run()
 */
public void run()
{
    Thread.currentThread().setName("initiateSTream Thread");
    try
    {
        initiateStream();
        Thread.currentThread().interrupt();
    }
    catch (UnsupportedEncodingException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (InterruptedException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (ExecutionException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

我尝试在任何地方添加退货,尽管它可能会有所帮助。但没有运气。有人可以帮我弄这个吗?

编辑1:当我使用调试模式时,我可以看到“initiateSTream Thread”线程。主线程消失时仍在运行!

编辑2(解决方案):在主要方法中,我替换了:


Executor ex = Executors.newSingleThreadExecutor();
        ex.execute(client);

和:


Thread thread = new Thread(client);
thread.start();

现在我的节目在指定的流媒体时间后结束。但为什么?这两种方法有什么区别?!

4

0 回答 0