只要输入1我就只想打印learning...

  package a;

    import java.util.Scanner;

    class main extends Thread {
        static String n;

        Scanner reader = new Scanner(System.in);
        public void run() {
            n = reader.nextLine();
        }

        public static void main(String args[]) throws InterruptedException {
            (new Thread(new main())).start();
            n="5";
            System.out.println("1 = ON\n0 = OFF");
            while (n.equals("1")) {
                System.out.println("Learning..");
            }
        }
    }

最佳答案

如果要停止启动,最好始终保持两个线程,一个用于打印,另一个用于输入。尝试使用打击代码。对我来说很好。


  public class ThreadsStop {

    static String n="";

    class Printer extends Thread{

        @Override
        public void run() {

            while(!n.equals(null)){

                try {
                    Thread.sleep(1000);

                    if(n.trim().equals("1"))
                        System.out.println("Learning..");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

        }

    }

    class Starter extends Thread{

        @Override
        public void run() {

            Scanner reader = new Scanner(System.in);

            while(true){
                System.out.println("1 = ON \n 0 = OFF");
                n= reader.nextLine();
            }
        }

    }

    public static void main(String[] args) {

        new ThreadsStop().start();

    }

    private void start() {

        new Starter().start();
        new Printer().start();

    }

}

09-26 15:38