Java多線程編程中如何傳遞線程參數(shù)

小樊
84
2024-08-30 08:57:21
欄目: 編程語言

在Java多線程編程中,可以通過實(shí)現(xiàn)Runnable接口或繼承Thread類來創(chuàng)建線程。為了向線程傳遞參數(shù),可以使用構(gòu)造函數(shù)或者實(shí)例變量。下面是兩種方法的示例:

  1. 實(shí)現(xiàn)Runnable接口:
class MyRunnable implements Runnable {
    private String param;

    public MyRunnable(String param) {
        this.param = param;
    }

    @Override
    public void run() {
        System.out.println("線程參數(shù): " + 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();
    }
}
  1. 繼承Thread類:
class MyThread extends Thread {
    private String param;

    public MyThread(String param) {
        this.param = param;
    }

    @Override
    public void run() {
        System.out.println("線程參數(shù): " + param);
    }
}

public class Main {
    public static void main(String[] args) {
        String param = "Hello, World!";
        MyThread myThread = new MyThread(param);
        myThread.start();
    }
}

在這兩個(gè)示例中,我們分別使用構(gòu)造函數(shù)將參數(shù)傳遞給MyRunnable和MyThread類。然后在run()方法中使用這些參數(shù)。最后,在主方法中創(chuàng)建線程并啟動(dòng)它。

0