Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am working with threads. However when I try to start a thread, I get a Exception. In concrete java.lang.IllegalThreadStateException. My code is:

public void readCommand() {
    readThread = new Thread("Thread for reading") {
        public void run() {
            while (running) {
                readBuffer = usbservice.receiveData();
                put(readBuffer);
            }
        }
    };
    readThread.start();
}

What could the problem be?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
667 views
Welcome To Ask or Share your Answers For Others

1 Answer

You are storing the thread in a field. If the method is called in two threads, the readThread.start() can be called twice for the same thread. You need to ensure readCommand is not called multiple times and perhaps not start the readThread again if its already running. e.g. you can synchronized the method and check readThread before you start.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...