Print to console while waiting for input in java?

2019-08-10 12:49发布

i want to print to console while waiting for input. Can this be done with multi-threading? If so, i dont know how to multi-thread. I need help!

2条回答
成全新的幸福
2楼-- · 2019-08-10 13:19

use this code:

     public class KeyboardInput extends Thread{
        Scanner sc= new Scanner(System.in);
        @Override
        public void run()
        {
        while(true)
        {
        sc.hasNext();
        }

    }

}

Then just call this when you want to start the input:

Thread t1= new Thread(new KeyboardInput);
t1.start();

Now you have a thread that reads inputs while the main thread is free to print to screen

EDIT: be sure to only call the thread once!

查看更多
一夜七次
3楼-- · 2019-08-10 13:21

I am not sure if I understand your question but this is possible solution. There are two new threads created in main method. First read from console and write text back to it and second is only counting down from 50 to 0 and writing to console actual number:

public class App {
    public static void main(String[] args) {
        new Thread(new ReadRunnable()).start();
        new Thread(new PrintRunnable()).start();
    }
}

class ReadRunnable implements Runnable {

    @Override
    public void run() {
        final Scanner in = new Scanner(System.in);
        while(in.hasNext()) {
            final String line = in.nextLine();
            System.out.println("Input line: " + line);
            if ("end".equalsIgnoreCase(line)) {
                System.out.println("Ending one thread");
                break;
            }
        }
    }

}

class PrintRunnable implements Runnable {

    @Override
    public void run() {
        int i = 50;
        while(i>0) {
            System.out.println("Beep: " + i --);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                throw new IllegalStateException(ex);
            }
        }
        System.out.println("!!!! BOOM !!!!");
    }
}
查看更多
登录 后发表回答