+ 2
Java Threads
I am trying to write a code where users inputs answer within a particular time. In my code I have created two files, one that handles the user input and contains the main method, with the second file which contains a class that extends the timer class to control the time factor of the code. So my code notifies the main method when the time is up, but it still waits for the user to input even after time is up. What I want to program to do is exit the main method and end the program completely even if the user hasn't entered the value when time is up.
7 Antworten
+ 1
You can check this thread too, there are two different solutions.
https://stackoverflow.com/questions/44038081/set-time-limit-on-user-input-scanner-java
+ 2
This the Main.java file:-
package Test;
import java.util.*;
import Timer.*;
public class Main implements Runnable {
public void run(){}
public static Main obj;
public static void main(String[] args) throws InterruptedException
{
obj = new Main();
Timer timer = new Timer();
TimerTask task = new Pack();
Date date = new Date();
Scanner sc = new Scanner(System.in);
String str;
timer.scheduleAtFixedRate(task, date, 5000);
System.out.println("Timer running");
synchronized(obj){
str = sc.nextLine();
//obj.wait();
timer.cancel();
//System.out.println(timer.purge());
System.out.println(str);
}
}
}
}
}
This is the Pack.java file:-
package Timer;
import java.util.*;
import Test.*;
public class Pack extends TimerTask {
public static int i = 0;
public void run(){
Main run = new Main();
Thread t = new Thread(run);
System.out.println("Timer " + ++i);
if(i == 4)
{
synchronized(Main.obj){
//notifies main method
Main.obj.notify();
t.interrupt();
}
}
}
}
this is my attempt for now, i will add my actual code in synchronised(obj) in main when this works correctly.
+ 2
If you are new to Java, in my opinion messing around with threads and concurrency maybe be reaching way over your head. :)
I imagine a newbie would be also shocked by things like AtomicBoolean or ScheduledExecutorService.
If you want to learn more about BufferedReader, I recommend to read this post:
https://www.baeldung.com/java-buffered-reader
+ 1
Please share your attempt
+ 1
Since I am new to java can you explain what this line means and does?
BufferedReader in = new BufferedReader(
new InputStreamReader( System.in ) );
+ 1
Actually AtomicBoolean and ScheduledExecutorService did go above my head🥲 hence I skipped that method and tried the first one which is working. Thank you for your help, appreciate it
+ 1
Linkin Park fans 🤘