import java.io.*;
public class ThreadSanbox {
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable(){
@Override
public void run()
{
StopThread stX = new StopThread();
boolean runLoopX = true;
while (runLoopX) {
System.out.println("runLoopX val: "+runLoopX);
runLoopX = stX.getRunLoop();
}
System.out.println("runLoopX val: "+ runLoopX);
}
});
Thread t2 = new Thread(new Runnable(){
@Override
public void run()
{
BufferedReader userInput = new BufferedReader(
new InputStreamReader(System.in));
String userInputStr = "";
StopThread st = new StopThread();
int count = 0;
do {
try {
System.out.println("Enter a value:");
userInputStr = userInput.readLine().trim();
System.out.println("User Input: " + userInputStr);
count++;
} catch (Exception e) {System.err.println(e.toString());}
} while (userInputStr.equals("e") == false);
st.setRunLoop(false);
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (Exception e) {System.err.println(e.toString());}
}
}
class StopThread
{
private boolean runLoop = true;
public synchronized boolean getRunLoop() {return runLoop;}
public synchronized void setRunLoop(boolean val) {runLoop = val;}
}
In the above code I want to run threads t1 and t2. In t2 i want to get input from the keyboard and if the input is e i want to exit the do while and set the value of runLoop to false so that the while loop in t1 also exits. How do I do this?
The problem is that your two threads have two separate instances of
StopThread. You need them to share a single instance so that they can communicate.One way to do this is to create subclasses of Thread or Runnable so that you can pass the shared StopThread instance into each of them in their constructors.
Another way is to make a simple variable in the enclosing class (both threads will be able to ‘see’ this variable so they can use it to communicate).