繁体   English   中英

无法在Java中运行两个线程

[英]Can't run two threads in Java

我在用Java运行这两个线程时遇到麻烦。 我在客户端类中有两个方法,在每个方法中它们都有一个不同端口的套​​接字,但是当我运行客户端时,我看到一个线程瞬间的错误,而另一个线程通过工作发送文件。

有什么帮助吗?

ClientApp.java

public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException {
    Thread getFileThread = new Thread() {
        public void run() {
            Client client = new Client();

            try {
                client.getTheFile("girlwithmask.jpg");
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };


    Thread getListOfFilesThread = new Thread() {
        public void run() {
            Client client = new Client();

            ArrayList<String> listOfFiles = null;
            try {
                listOfFiles = client.getFileList();
                System.out.println(listOfFiles.get(1));
                notify();
            } catch (ClassNotFoundException | IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

    getListOfFilesThread.start();
    getFileThread.start();
}

客户端.java

    public class Client {
        private static final int PORT = 2665;
        private static String HOST = "localhost";

        Client() {

        }

        public void getTheFile(String filename) throws UnknownHostException, IOException {
            filename = "girlwithmask.jpg";  ///this is temporary

            int filesize = 5000000;   //buffer size 5mb
            int bytesRead;
            int currentTotalNumberOfBytes = 0;

            //connect to port on server - server waits for this after running socket.accept() in the Server class
            Socket socket = new Socket(HOST, PORT);

            byte[] byteArray = new byte[filesize];   //create a byte array of 5mb
            InputStream inputStream = socket.getInputStream();  //channel to to server
            FileOutputStream fileOutStream = new FileOutputStream("myClientFiles/" + filename);
            BufferedOutputStream bufferOutStream = new BufferedOutputStream(fileOutStream);

            bytesRead = inputStream.read(byteArray, 0, byteArray.length);
            currentTotalNumberOfBytes = bytesRead;

            do { //read till the end and store total in bytesRead and add it to currentTotalNumberOfBytes
                bytesRead = inputStream.read(byteArray, currentTotalNumberOfBytes, (byteArray.length - currentTotalNumberOfBytes));
                if (bytesRead >= 0) {
                    currentTotalNumberOfBytes += bytesRead;
                }
            } while (bytesRead > -1); // when bytesRead == -1, there's no more data left and we exit the loop

            bufferOutStream.write(byteArray, 0, currentTotalNumberOfBytes); //write the bytes to the file

            bufferOutStream.flush();
            bufferOutStream.close();
            socket.close();

        }

        public ArrayList<String> getFileList() throws UnknownHostException, IOException, ClassNotFoundException {
            Socket socket = new Socket("localhost", 9999);
            ArrayList<String> titleList = new ArrayList<String>();

            ObjectInputStream objectInput = new ObjectInputStream(socket.getInputStream());

            Object object = objectInput.readObject();
            titleList = (ArrayList<String>) object;
            // System.out.println(titleList.get(2));

            return titleList;
        }
    }

我不确定这是怎么回事。 已经使用了几个小时。

在没有实际错误或确实问题的情况下,我们所能做的就是对您的代码进行批判:

 byte[] byteArray = new byte[filesize];   //create a byte array of 5mb

您不知道什么是filesize 您已经硬编码了5000000的猜测值 。在文件大小大于5000000的情况下(这可能经常出现),这将不起作用。 在一种方法中,您不需要知道文件大小:首先也不需要缓冲区来缓冲整个文件的大小。 您假设文件适合内存并且文件长度适合int. 两种假设都可能是错误的。 使用较小的8192缓冲区大小或一些合理的数字(通常为1024的倍数)以获得良好的内存对齐。 硬编码500万的大尺寸具有上述缺点。

InputStream inputStream = socket.getInputStream();  //channel to to server
FileOutputStream fileOutStream = new FileOutputStream("myClientFiles/" + filename);
BufferedOutputStream bufferOutStream = new BufferedOutputStream(fileOutStream);

您实际上不需要BufferedOutputStream带有此代码,或者至少不需要此代码,但现在就让它通过。

bytesRead = inputStream.read(byteArray, 0, byteArray.length);
currentTotalNumberOfBytes = bytesRead;
do { //read till the end and store total in bytesRead and add it to currentTotalNumberOfBytes
    bytesRead = inputStream.read(byteArray, currentTotalNumberOfBytes, (byteArray.length - currentTotalNumberOfBytes));
    if (bytesRead >= 0) {
        currentTotalNumberOfBytes += bytesRead;
    }
} while (bytesRead > -1); // when bytesRead == -1, there's no more data left and we exit the loop
bufferOutStream.write(byteArray, 0, currentTotalNumberOfBytes); //write the bytes to the file

为了使这段代码更短,您可能需要将其更改为规范形式:

int count;
byte[] buffer = new byte[8192];
while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}

适当地替换变量名。 你会:

  1. 节省记忆
  2. 减少延迟
  3. 具有已经使用了18年的经过良好测试的清晰代码。

     bufferOutStream.flush(); 

close() flush()之前的flush()是多余的。

    bufferOutStream.close();
    socket.close();

关闭套接字的输出流(或输入流)后关闭套接字是多余的。 只需关闭输出流。 finally一块。

暂无
暂无

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

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