Search code examples
javamultithreadingreal-timejava-threads

JAVA real time consol-control the threads


I am a beginner in programming. I am still learning about threads and more of them. But now I have quite a big idea to write my first program (I mean bigger than simple calculator). I want it to sort files, integrate in one (many copies of one file in different localization - the idea of it is of no importance now).

But I want to create threads, or anything else (what is your advice). I mean. When I start the program, the console starts up, and e.g I have to write "my_programm run" or "my_program stop" or "my_program status" or "my_magic_tricks be_done". I mean how can i create a program working in the background like in threads with real time string control over it. I tried to find out on Google for anything which could be useful for me, but i didn't find it out.

Please give me just a name of libraries or methods, which I can use. I will read out, what it is about and finally I will move forward with it.

If it is a dumbass question. I am really sorry for disapointing the programmer group. But it would be nice to be given of any signpost or clue.


Solution

  • A simple way to do it using the standard library :

    import java.util.Scanner;
    import java.util.concurrent.LinkedBlockingDeque;
    import java.util.concurrent.ThreadPoolExecutor;
    
    import static java.util.concurrent.TimeUnit.MILLISECONDS;
    
    public class Example {
        private static final int POOL_SIZE = 5;
        private static final ExecutorService WORKERS = new ThreadPoolExecutor(POOL_SIZE, POOL_SIZE, 1, MILLISECONDS, new LinkedBlockingDeque<>());
    
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            while (true) {
                System.out.print("> ");
                String cmd = sc.nextLine();
                switch (cmd) {
                    case "process":
                        WORKERS.submit(newExpensiveTask());
                        break;
    
                    case "kill":
                        System.exit(0);
    
                    default:
                        System.err.println("Unrecognized command: " + cmd);
                }
            }
        }
    
        private static Runnable newExpensiveTask() {
            return () -> {
                try {
                    Thread.sleep(10000);
                    System.out.println("Done processing");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            };
        }
    }
    

    This code lets you run heavy tasks asynchronously while the user terminal remains available and reactive.