简体   繁体   English

创建了新线程,但没有运行(java)

[英]new thread is created, but doesn't run (java)

here's a little code I wrote. 这是我写的一些代码。 This next class waits for a connection and creates a new thread upon receiving one: 下一个类等待连接,并在收到一个连接后创建一个新线程:

    ServerSocket serverSocket = null;
    ExecutorService serv = Executors.newCachedThreadPool();
    serv.execute(new UserThread());
    try {
        serverSocket = new ServerSocket(FMDataManager.getPort());
        serverSocket.setSoTimeout(0);
        while (_listening){
            System.out.println("Listening on port "+FMDataManager.getPort());
            System.out.println("Waiting for connections.");
            serv.execute(new UploadThread(serverSocket.accept()));          
        }
    } catch (IOException e) {
        System.err.println("Could not listen on port: "+FMDataManager.getPort()+".");
        System.exit(-1);
    }

as you can see i am using ServerSocket.accept() method to wait for a connection. 如您所见,我正在使用ServerSocket.accept()方法来等待连接。 The thread is indeed created, but it won't run. 线程确实已创建,但不会运行。 I put a little "thread created" in its constructor and another message "starting thread" in run(), but I only got the first message. 我在其构造函数中添加了一个“创建的线程”,并在run()中添加了另一条消息“正在启动线程”,但是我只有第一条消息。 After that it didn't do anything, I didn't even get "thread created". 在那之后它什么也没做,我什至没有得到“创建线程”的信息。 Any ideas please? 有什么想法吗?

I've add the implementation of the UploadThread I am trying to start, maybe It'll help 我添加了我要开始的UploadThread的实现,也许会有所帮助

public class UploadThread extends Thread{

Socket _socket;

public UploadThread(Socket socket) {
    super("UserThread");
    _socket = socket;
}
public void run(Socket socket) {
    System.out.println("entred upload thread");
    DataOutputStream out = null;
    DataInputStream in = null;
    try {
        out = new DataOutputStream(_socket.getOutputStream());
        in = new DataInputStream(_socket.getInputStream());
        FileMessage inputMessage;
        SendFile outputMessage;
        inputMessage = (FileMessage) CommandEnum.readMessage(in);
        System.out.println("F: "+inputMessage.getCaption());
        File file = null;
        Iterator<File> itr = FMDataManager.getFiles().iterator();
        while (itr.hasNext()){
            File temp = itr.next();
            if (temp.getName().equals(inputMessage.getFile()))
                file = temp;
        }
        outputMessage = new SendFile(file);
        outputMessage.send(out);
    } catch (IOException e) {
        e.printStackTrace();
    } finally{
        try {
            _socket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
}

Try serv.submit instead of serv.execute . 尝试使用 serv.submit而不是 serv.execute

EDIT 编辑

Looks like UploadThread isn't overriding run() correctly. 看起来UploadThread没有正确覆盖run() That being said, your run method declaration should look like this: 话虽如此,您的run方法声明应如下所示:

@Override
public void run(){
    //do stuff
}

There's no need to pass socket as an argument. 无需将socket作为参数传递。

As indicated by sthupahsmaht's comment your UploadThread implementation is wrong. 如sthupahsmaht的评论所示,您的UploadThread实现是错误的。 The signature for the run() method is public void run() . run()方法的签名是public void run() Currently you are creating a new method with the signature public void run(Socket) . 当前,您正在使用签名public void run(Socket)创建一个新方法。 As run() doesn't take any arguments you have to pass all parameters via the constructor or setters. 由于run()不接受任何参数,因此您必须通过构造函数或setter传递所有参数。

There are two best practices that can help you avoid such mistakes in the future: 有两种最佳做法可以帮助您将来避免此类错误:

  • Whenever you implement or override a method, annotate it with @Override . 每当您实现或重写方法时,请使用@Override对其进行注释。 If you create a new method with @Override , the compiler signals an error. 如果使用@Override创建新方法,则编译器会发出错误消息。
  • Don't extend Thread but implement Runnable . 不要扩展Thread而是实现Runnable Thread has a default implementation for run() which does nothing. Thread具有run()的默认实现,该默认实现不执行任何操作。 This is what happens with your code currently. 这就是您的代码当前发生的情况。

Without seeing the part of the code that actually constructs the thread, I'll guess you're NOT calling the 'start()' method on the thread object. 在没有看到实际构造线程的代码部分的情况下,我想您不会在线程对象上调用'start()'方法。

Needs to be something like this: 需要是这样的:

Thread thr = new Thread(new Runnable() { void run() { /* do stuff */ }) ;

thr.start() // GO!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM