我想使用多线程将文件拆分成块,我正在尝试但是,我不知道如何使用多线程代码的正确方法,因为我是多线程的新手。我的主要目标是降低CPU利用率并快速完成文件的拆分。请帮助我如何在我的代码中使用多线程。 提前谢谢。
一些代码
public class ServerSocketThread implements Runnable {
@Override
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
infoPort.setText("I'm waiting here: " + serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
FileTxThread fileTxThread = new FileTxThread(socket);
fileTxThread.start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class FileTxThread implements Runnable {
Socket socket;
FileTxThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
BufferedInputStream bis;
ArrayList<byte[]> al = new ArrayList<byte[]>();
final int cSize = 64 * 1024;
File file = new File(Environment.getExternalStorageDirectory(), "test.mp3");
byte[] bytes = new byte[2048];
bis = new BufferedInputStream(new FileInputStream(file));
OutputStream os = socket.getOutputStream();
int read;
final double pieces = file.length() / 2048; // used to return file length.
int fileSize = (int) file.length();
int readlen = 1024;
// for (int i = 0; i <= pieces; i++) {
// System.out.println("If loop" + i);
while (fileSize > 0) {
if (fileSize < 1024) {
readlen = fileSize;
System.out.println("Hello.........");
}
bytes = new byte[readlen];
read = bis.read(bytes, 0, readlen);
fileSize -= read;
al.add(bytes);
}
BufferedOutputStream out1 = new BufferedOutputStream(new FileOutputStream(Environment.getExternalStorageDirectory() + "/new.mp3"));
for (int ii = 1; ii < al.size(); ii++) {
out1.write(al.get(ii));
// out1.flush();
}
out1.close();
File file1 = new File(Environment.getExternalStorageDirectory(), "new.mp3");
System.out.println("File1 length output " + file1.length());
谢谢!