java - Why not to start a thread in the constructor? How to terminate? -
i learning how use threads in java. , wrote class implements runnable run concurrently thread. main thread handles listening serial port second thread handle sending data 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 second this:
public class main { public static void main(string[] args) throws exception{ new mynewthread(); // first thread code there } } this works complier flags warning saying: dangerous start new thread in constructor. why this?
the second part question is: how if have loop running in 1 thread (the serial port listen thread) , type exit command in second thread. how first thread terminate? thanks.
to first question: starting thread in constructor passing in this escapes this. means giving out reference object before constructed. thread start before constructor finishes. can result in kinds of weird behaviors.
to second question: there no acceptable way force thread stop in java, use variable thread check know whether or not should stop. other thread set indicate first thread stop. variable has volatile or accesses synchronized ensure proper publication. here code want.
public class mynewthread implements runnable { private final thread t; private volatile boolean shouldstop = false; mynewthread() { t = new thread (this, "data thread"); } public void start() { t.start(); } public void stop() { shouldstop = true; } public void run() { while(!shouldstop) { // stuff } } } whatever wants create , start thread do:
mynewthread thread = new mynewthread(); thread.start(); whatever wants stop thread do:
thread.stop();
Comments
Post a Comment