我的程序不起作用,如何改善示例?

在此代码中是错误的。 Eclipse在一行中说Cannot instantiate the type SynchroRunnable 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();
    }

最佳答案

我认为您的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
    }
}

关于java - 如何将参数传递给Java线程?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34519096/

10-11 00:19