Search code examples
javamultithreadingprogram-entry-point

Put a main function args inside the thread in java


I'm having a problem with threads in java . This is my class that implements thread :

public class SensorAddClient extends Thread implements Runnable {
String[] args = new String[3];
@Override
public void run(){
try {
    SensorClient.main(args);//this is the main function i wanna get executed on my args
} catch (IOException e) {
    e.printStackTrace();
} catch (JSONException e) {
    e.printStackTrace();
}}

then i use the next 2 following lines to call it when i need to activate the thread:

SensorAddClient cl = new SensorAddClient(); cl.start();

I have to start a thread whose run just has to call a specific class which executes using the args, so i call the main function of the class,is there any way to make the main function of the class i call to get executed with the args i want? So ho can i put elements on that : String[] args = new String[3]; before executing the run of the thread? Is that possible ? Any help would be appreciated, thank you in advance :)


Solution

  • Create a constructor and add the values there:

    public class SensorAddClient extends Thread implements Runnable {
    String[] args = new String[3];
    
    public SensorAddClient(String[] args) {
    
     this.args = args;
    
    }
    @Override
    public void run(){
    try {
        SensorClient.main(args);//this is the main function i wanna get executed on my args
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }}