簡體   English   中英

在不同的線程中運行類方法

[英]Run class methods in different threads

假設我有這個課:

public class Myclass {
    method1();
    method2();
    method3();
}

我想知道是否有一種方法可以同時在不同線程中運行所有3個方法。

有沒有辦法創建一個類MyThread

public class MyThread{
    //implementation
}

可以接受myclass::method1()作為參數的方式

這樣我的主要功能看起來像這樣:

public static void main(String[] args) {
    Myclass myclass = new Myclass();
    MyThread mythread1 = new MyThread();
    MyThread mythread2 = new MyThread();
    MyThread mythread3 = new MyThread();

    mythread1(myclass.method1()); 
    mythread2(myclass.method2());
    mythread3(myclass.method3());
}

我希望mythread()在線程中運行method()mythread()在線程中使用它的輸出。

如果您使用的是Java 8,則可以執行以下操作:

public static void main(String[] args) {
    new Thread(MyClass::method1).start();
    new Thread(MyClass::method2).start();
    new Thread(MyClass::method2).start();
}

在Java 7及以下版本中,語法還有更多內容:

public static void main(String[] args) {
    new Thread (new Runnable () {
        @Override
        public void run ()
        {
            method1 ();
        }
    }).start();
}

為了簡潔起見,我只展示了一種方法-您必須為要調用的每種方法重復new Theadstart()的所有操作。

public class HelloRunnable implements Runnable {
    private MyClass myClass;
    private boolean execMethod1;
    private boolean execMethod2;
    private boolean execMethod3;

public HelloRunnable(MyClass myClass, boolean execMethod1, boolean execMethod2, boolean execMethod3) {
    this.myClass = myClass;
    this.execMethod1 = execMethod1;
    this.execMethod2 = execMethod2;
    this.execMethod3 = execMethod3;
} 
public void run() {
    if(execMethod1) myClass.method1();
    else if(execMethod2) myClass.method2();
    else if(execMethod3) myClass.method3();
}

public static void main(String args[]) {
    MyClass myClass = new MyClass();
    (new Thread(new HelloRunnable(myClass, true, false, false))).start();
    (new Thread(new HelloRunnable(myClass, false, true, false))).start();
    (new Thread(new HelloRunnable(myClass, false, false, true))).start();
}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM