I got a question about multithreading. I'm still new at this.
I have a main program which only function is to invoke a input thread and a printer thread and then it does nothing else.
The input thread checks if there is input in the console. If yes, it's supposed to interrupt the printer thread. Unless it's a "q", the input thread will then go to sleep and then check again if there is any more input
The printer thread is supposed to check if it's interrupted. When it is, it's supposed to print the input.
I think I'm allowed to use notify as an alternative but I don't know how to use it either.
Here's my code. It currently comes out with an error
import java.util.Scanner;
public class Q2 {
public static void main(String[] args) {
/* creating a new thread and starting it */
Thread InThread = new Thread(new InputThread());
Thread PrintThread = new Thread(new PrinterThread());
InThread.start();
PrintThread.start();
}
}
class InputThread implements Runnable {
public static String theLine;
/* constructor for thread */
public InputThread() {
}
public void run() {
Scanner scan = new Scanner(System.in);
try {
System.out.println("Enter an input: ");
System.out.println("Press <Q> to exit");
theLine = scan.nextLine();
while (!theLine.equalsIgnoreCase("Q")) {
notify();
Thread.sleep(3000);
theLine = scan.nextLine();
}
System.out.println("String input complete...");
} catch (Exception e) {
System.out.println("Error has occured!");
}
return;
}
}
class PrinterThread implements Runnable {
/* constructor for thread */
public PrinterThread() {
}
public void run() {
while (true) {
try {
wait();
if(!InputThread.theLine.equalsIgnoreCase("Q")){
System.out.println(InputThread.theLine);
}else{
return;
}
}catch(InterruptedException e){
System.out.println("Thread was interrupted");
return;
}
}
}
}
I mostly don't know how to use notify(), wait() and interrupt() in this situation.