如何将参数传递给Java线程?

时间:2015-12-29 21:06:21

标签: java multithreading parameters

我的计划不起作用,我该如何改进我的榜样?

在这段代码中是错误的。 Eclipse在行Cannot instantiate the type Synchro

中说Runnable threadTask = new Synchro(param1, param2);
button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        synchronizuj.setEnabled(false);
        String param1 = main_catalog.getText();
        String param2 = copy_catalog.getText();
        Runnable threadTask = new Synchro(param1, param2);
        Thread newThread = new Thread (threadTask);
        newThread.start();
    }
}); 
另一个文件中的

和类Synchro :(此代码适用于Eclipse)

public abstract class Synchro implements Runnable { 
    private String argument1;
    private String argument2;

    public void run(String argument1, String argument2) {
        this.argument1 = argument1;
        this.argument2 = argument2;
        sleepThread();
    }

2 个答案:

答案 0 :(得分:1)

我认为你的Synchro课应该是这样的。

public class Synchro implements Runnable {
    private String argument1;
    private String argument2;

    // the arguments pass by constructor
    public Synchro(String argument1, String argument2) {
        this.argument1 = argument1;
        this.argument2 = argument2;
    }

    // you have to override run method, when you implement Runnable interface
    @Override
    public void run() {
        // your code
    }
}

答案 1 :(得分:1)

这是另一种适用于Java8的方法:

button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        synchronizuj.setEnabled(false);
        final String param1 = main_catalog.getText();
        final String param2 = copy_catalog.getText();
        Thread newThread = new Thread (() -> {
            ...code to be executed in the thread goes here.
               It can refer to param1 and param2,
               but it can not change them...

        });
        newThread.start();
    }
});

new Thread(...)的参数是 lambda表达式 ---一种定义和实例化实现功能接口的匿名内部类的简洁方法(注意) :Runnable已在Java8中重新定义为功能接口。)