java.lang.IllegalThreadStateException [英] java.lang.IllegalThreadStateException

查看:65
本文介绍了java.lang.IllegalThreadStateException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用线程。但是,当我尝试启动一个线程时,我得到一个例外。具体来说就是java.lang.IllegalThreadStateException。我的代码是:

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();
}

问题是什么?

推荐答案

您正在将字符存储在字段中。如果在两个线程中调用该方法,则可以为同一个线程调用 readThread.start()两次。您需要确保多次调用readCommand,如果已经运行,则可能无法再次启动readThread。例如你可以在开始之前同步方法并检查readThread。

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.

这篇关于java.lang.IllegalThreadStateException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆