如何从主方法将值传递到Java runnable的run()函数中

时间:2018-12-11 15:38:39

标签: java runnable

此处尝试将id传递给run()函数,但它会打印Cannot resolve symbol id

public class main2 implements Runnable {

    public main2(int id) {
        //
    }

    public void run() {
        System.out.println("ID in the run: " + id); // Cannot resolve symbol id
    }

    public static void main(String args[]) throws InterruptedException {
        int id = 5;
        System.out.println("ID in the main: " + id);
        Thread[] threads = new Thread[1];
        threads[0] = new Thread(new main2(id));
        threads[0].start();
    }
}

3 个答案:

答案 0 :(得分:2)

您可以在main2类中包含一个实例字段:

public class main2 implements Runnable {
    private int id;
    public main2(int id) {
        this.id = id;
    }

    @Override
    public void run() {
        System.out.println("ID in the run: " + this.id);
    }

    ...

但是,由于所有这些都在同一类中,因此您可以简单地使用可以访问main方法的局部变量的lambda表达式,这也将消除对main2实例的需求:

public static void main(String args[]) throws InterruptedException {
    int id = 5;
    System.out.println("ID in the main: " + id);
    Thread[] threads = new Thread[1];
    threads[0] = new Thread(() -> System.out.println("ID in the run: " + id));
    threads[0].start();
}

答案 1 :(得分:1)

由于您的“主”类具有方法run(),因此可以在其中包含字段变量,并让构造函数设置其值。 您已经在使用构造函数来获取值。您只需要创建一个新的字段变量并设置其值即可。

public class main2 implements Runnable {
int id;
public main2(int id) {
    this.id = id;
}

public void run() {
    System.out.println("ID in the run: "+id); // Cannot resolve symbol id
}

public static void main(String args[]) throws InterruptedException {
    int id = 5;
    System.out.println("ID in the main: "+id);
    Thread[] threads = new Thread [1];
    threads[0] = new Thread(new main2(id));
    threads[0].start();
}

答案 2 :(得分:0)

只需将其设置为类的变量即可。然后您可以访问它:

private int id;    

public class main2 implements Runnable {
    public main2(int id) {
        this.id = id;
    }

public void run() {
    System.out.println("ID in the run: "+id); // Cannot resolve symbol id
}