简体   繁体   中英

How can I pass a parameters to a Java Thread?

My program doesn't work, how can I improve my example?

In this code is mistake. Eclipse say Cannot instantiate the type Synchro in line: 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();
    }
}); 

and class Synchro in another file: (this code is ok for 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();
    }

I thing your Synchro class should look like this.

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
    }
}

Here's another way that works in 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();
    }
});

The argument to new Thread(...) is a lambda expression ---a compact way of defining and instantiating an anonymous inner class that implements a functional interface (Note: Runnable has been re-defined in Java8 as a functional interface.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM