[英]How to run a class' method using thread
如果執行以下操作,則可以將對象創建為線程並運行它。
class ThreadTest
{
public static voic main(String[] args)
{
HelloThread hello = new HelloThread();
Thread t = new Thread(hello);
t.start();
}
}
class HelloThread extends Thread
{
public void run()
{
System.out.println(" Hello ");
}
}
現在,如果我的HelloThread
類有另一個方法調用runThisPlease()
,我們應該如何用線程運行它?
例:
class HelloThread extends Thread
{
public void run()
{
System.out.println(" Hello ");
}
public void runThisPlease(String input)
{
System.out.println (" Using thread on another class method: " + input );
}
}
Thread t = new Thread(hello.runThisPlease());
:當我嘗試Thread t = new Thread(hello.runThisPlease());
,它不起作用。 那么如何使用線程調用方法runThisPlease()
?
編輯: runThisPlease()
方法中需要的參數;
在Java 8中,您可以使用
Thread t = new Thread(hello::runThisPlease);
hello::runThisPlease
將通過調用hello.runThisPlease();
的run方法轉換為Runnable
hello.runThisPlease();
。
如果要調用需要參數的方法,例如System.out.println
,則當然也可以使用普通的lambda表達式:
final String parameter = "hello world";
Thread t = new Thread(() -> System.out.println(parameter));
如果使用的Java版本<8,則當然可以將方法reference / lambda表達式替換為可擴展Runnable
匿名內部類(這是Java8編譯器執行的操作,即AFAIK),請參見其他答案。
但是,您也可以使用擴展Thread
的匿名內部類:
final HelloThread hello = //...
Thread t = new Thread() {
@Override
public void run() {
hello.runThisPlease();
}
};
只需從run()
方法中調用runThisPlease()
,它將使其成為新線程的一部分。
嘗試這個:
class HelloThread extends Thread
{
public void run()
{
System.out.println(" Hello .. Invoking runThisPlease()");
runThisPlease();
}
public void runThisPlease()
{
System.out.println (" Using thread on another class method ");
}
}
您只需要在run()
方法內調用此方法。
public void run(){
System.out.println(" Hello ");
runThisPlease();
}
如果您想傳遞一些參數,則可以使用以下代碼
String str = "Welcome";
Thread t = new Thread(new Runnable() {
public void run() {
System.out.println(str);
}});
如果使用Runnable接口,情況可能會更加清楚:
public class HelloThread implements Runnable
{
@Override
public void run() {
// executed when the thread is started
runThisPlease();
}
public void runThisPlease() {...}
}
要發起此呼叫:
Thread t=new Thread(new HelloThread());
t.start();
Thread類看不到您的額外方法,因為它不是Runnable接口的一部分。 為了方便起見,線程實現了Runnable,但我認為它沒有幫助:(
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.