nooby nooby - 4 months ago 16
Java Question

Console application with two threads

I just want to print

learning...
as long as I enter 1

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..");
}
}
}

Answer

If you are trying to stop start, it is always better to maintain two threads one for printing and other for taking input. Try with blow code. It is working fine for me.


  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();

    }

}
Comments