Jin Yu Li
Jin Yu Li

Reputation: 103

Running Two Threads in Main Method

Is it possible to choose which thread to run in the main method? for example:

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
        System.out.print("How many entries do you want to make? ");
        entries = input.nextInt();
        System.out.print("\nPlease enter your choice:\n ");
        System.out.print("\n1. Specific file");
        System.out.println("\n2. All files\n");
        userChoice = choiceScanner.nextInt();
        if (userChoice == 1)
           new Thread(new GUIGenerator(entries)).start();
        if (userChoice == 2)
           new Thread(new GUIGenerator2(entries)).start();
        }
    });
}

Here, what I want to do is have the program run either the first or second thread depending on what the user enters. Is this possible, or can main only take one thread?

Upvotes: 0

Views: 657

Answers (3)

nasukkin
nasukkin

Reputation: 2540

"Is it possible to choose which thread to run in the main method?"

YES

Rational is that you already did it in your example. There is nothing stopping you from writing logic (such as the if-else conditional you provided) that fires up one implementation of your thread vs another.

Upvotes: 0

Dici
Dici

Reputation: 25950

The whole point of SwingUtilities.invokeLater is that you pass a runnable and Swing runs it for you when it can. You're not supposed to run stuff by yourself if it's going to interact with the UI, because there's only one application thread rendering the graphic components. Just by the looks of it, this snippet seems incorrect.

I don't see why you would need to create a new thread at this point, you just need to call whatever code is contained in GUIGenerator.run and GUIGenerator2.run.

Upvotes: 1

Patrick Bell
Patrick Bell

Reputation: 769

The whole idea behind multithreading is that it allows your code to executing instructions in parallel (that is, at the same time.) So if you start a new Thread from your main, your new Thread will begin its execution, and your Main will continue along to the next instruction as if the Thread never happened. So yes, it is very possible to execute both a new Thread AND the initial program flow at the same time.

Upvotes: 1

Related Questions