在方法内调用runnable并传递对象

时间:2015-06-18 08:45:43

标签: java android

我正在尝试调用一个可运行的线程,该线程将项放入LinkedBlockingList。我现在面临的问题是我无法运行内部方法。只有外部方法正在运行。我知道我必须在评论中添加以下代码行,但我真的很无能为力。

public void prod(TwitterObj obj) {
System.out.println("Prod Outer");
class Producer implements Runnable {

    TwitterObj obj;
    @Override
    public void run() {
        try {
            queue.put(obj);
            System.out.println("Put OBJ into queue: " + obj.getMsg());
            ++i;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    };

    //invoke thread
}}

正在显示“Prod Outer”消息但内部类根本没有运行。任何反馈将不胜感激!

编辑1:

这是我的代码,我听自己的Twitter流并将值添加到对象

    public void onStatus(twitter4j.Status status) {
                System.out.println("onStatus @" + status.getUser().getScreenName() + " - " + status.getText() + " - " + status.getCreatedAt());

                obj.setMsg(status.getText());
                obj.setDateTime(String.valueOf(status.getCreatedAt()));
                obj.setId((int) status.getId());
                prod(obj);
            }

1 个答案:

答案 0 :(得分:1)

如果您想知道如何将TwitterObj传递给Runnable,那么该怎么做。

class Producer implements Runnable {
    private TwitterObj obj;

    public Producer(TwitterObj obj) {
        this.obj = obj;
    }

    @Override
    public void run() {
        try {
            queue.put(obj);
            System.out.println("Put OBJ into queue: " + obj.getMsg());
            ++i;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    };
}

现在您可以创建一个Producer,如下所示:

TwitterObj twitterObj = ....;

Producer producer = new Producer(twitterObj);
Thread t = new Thread(producer);
t.start();

特别是替换

public void onStatus(twitter4j.Status status) {
    System.out.println("onStatus @" + status.getUser().getScreenName() + " - " + status.getText() + " - " + status.getCreatedAt());

    obj.setMsg(status.getText());
    obj.setDateTime(String.valueOf(status.getCreatedAt()));
    obj.setId((int) status.getId());
    prod(obj);
}

public void onStatus(twitter4j.Status status) {
    System.out.println("onStatus @" + status.getUser().getScreenName() + " - " + status.getText() + " - " + status.getCreatedAt());

    obj.setMsg(status.getText());
    obj.setDateTime(String.valueOf(status.getCreatedAt()));
    obj.setId((int) status.getId());

    // prod(obj);  removed and replaced with the 3 lines below
    Producer producer = new Producer(twitterObj);
    Thread t = new Thread(producer);
    t.start();
}