I am learning how to use threads in Java. And I wrote a class that implements Runnable to run concurrently to another thread. The main thread handles listening to the serial port where as the second thread will handle sending data to that same port.
public class MyNewThread implements Runnable {
Thread t;
MyNewThread() {
t = new Thread (this, "Data Thread");
t.start();
}
public void run() {
// New Thread code here
}
There first thread starts the second like this:
public class Main {
public static void main(String[] args) throws Exception{
new MyNewThread();
// First thread code there
}
}
This works but my complier flags a warning saying: It is dangerous to start a new thread in the constructor. Why is this?
The second part to this question is: how if I have a loop running in one thread (the serial port listen thread) and I type an exit command in my second thread. How do I get the first thread to terminate? Thanks.