在Java多線程編程中,可以通過實現Runnable接口或繼承Thread類來創建線程。為了向線程傳遞參數,可以使用構造函數或者實例變量。下面是兩種方法的示例:
class MyRunnable implements Runnable {
private String param;
public MyRunnable(String param) {
this.param = param;
}
@Override
public void run() {
System.out.println("線程參數: " + param);
}
}
public class Main {
public static void main(String[] args) {
String param = "Hello, World!";
MyRunnable myRunnable = new MyRunnable(param);
Thread thread = new Thread(myRunnable);
thread.start();
}
}
class MyThread extends Thread {
private String param;
public MyThread(String param) {
this.param = param;
}
@Override
public void run() {
System.out.println("線程參數: " + param);
}
}
public class Main {
public static void main(String[] args) {
String param = "Hello, World!";
MyThread myThread = new MyThread(param);
myThread.start();
}
}
在這兩個示例中,我們分別使用構造函數將參數傳遞給MyRunnable和MyThread類。然后在run()方法中使用這些參數。最后,在主方法中創建線程并啟動它。