创建线程对象后调用实现runnable的Java类的方法 [英] Call the method of Java class which implements runnable after creating its thread object

查看:62
本文介绍了创建线程对象后调用实现runnable的Java类的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个java类

SomeClass implements Runnable

其中有一个方法 display().

Which has a method display().

当我创建这个类的线程时

When I create a thread of this class

Thread thread1 = new Thread(new SomeClass());

现在如何使用线程实例调用 display() 方法?

Now how I can call the display() method using the thread instance?

推荐答案

你最终会在 thread1 上调用 start().

You will end up calling start() on thread1.

SomeClass 将覆盖 run() 方法,该方法又需要调用 display() 方法.

SomeClass will override run() method which in turn need to call display() method.

这样当你调用start()时,SomeClass()对象的run方法会被调用,display()方法会被执行.

This way when you call start(), run method of SomeClass() object will be invoked and display() method will be executed.

示例:

public class SomeClass implements Runnable {
    private List yourArrayList;
    public void run() {
        display();
    }

    public void display() {
        //Your display method implementation.
    }
   public List methodToGetArrayList()
   {
    return  yourArrayList;
   }
}

更新:

SomeClass sc = new SomeClass()
Thread thread1 = new Thread(sc);
thread1.join();
sc.methodToGetArrayList();

注意:示例是为了说明概念,可能存在语法错误.

NOTE: Example is to illustrate the concept, there may be syntax errors.

如果不使用 join(),正如 Andrew 所说,结果可能会不一致.

If you don't use join(), as Andrew commented, there may be inconsitence in results.

这篇关于创建线程对象后调用实现runnable的Java类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆