Here is a quick example of how a multi-threaded command line interface application may work. This will not require polling for input, nor a GUI interface in order to perform tasks in the background while waiting for input from a user in a console.
In this example, a Thread
is running in the background, which can be told to output a greeting in a specified number of seconds later.
public class CommandLineMultiThread
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
// Makes and runs the background thread.
MyThread myThread = new MyThread();
Thread t = new Thread(myThread);
t.start();
// Get the number of seconds to wait from the console.
// Exit when "0" is entered.
int waitDuration;
do
{
waitDuration = s.nextInt();
myThread.setGreetIn(waitDuration);
} while (waitDuration != 0);
myThread.quit();
}
static class MyThread implements Runnable
{
boolean running = true; // Boolean to keep thread alive.
long greetingTime = Long.MAX_VALUE; // Time to greet at.
public void setGreetIn(int i)
{
greetingTime = System.currentTimeMillis() + (i * 1000);
}
public void quit()
{
running = false;
}
public void run()
{
while (running)
{
if (System.currentTimeMillis() > greetingTime)
{
System.out.println("Hello!");
greetingTime = Long.MAX_VALUE;
}
try
{
Thread.sleep(100);
}
catch (InterruptedException e) {}
}
}
}
}
The Scanner
class can be used to accept user input from the command line interface by routing the input from the System.in
object.
Then, while the background thread myThread
is running, the main thread is waiting for an input from System.in
via the Scanner.nextInt
method. Once the seconds to wait has been accepted, the background thread is told to wait until a certain time, and once that time arrives, the greeting Hello!
is output to the console.