如何一次完成多个任务?

时间:2016-02-06 21:13:13

标签: java

我怎么能一次下载2到3个文件,当1完成时它会再次下载?现在它做了它需要做的事情,但如果你一次下载30个视频需要一段时间,所以我希望它一次下载2个或3个。

try {
            URL url;
            byte[] buf;
            int byteRead, byteWritten = 0;
            url = new URL(getFinalLocation(fAddress));;
            outStream = new BufferedOutputStream(new FileOutputStream(destinationDir + "\\" + localFileName));

            uCon = url.openConnection();
            is = uCon.getInputStream();
            buf = new byte[size];
            while ((byteRead = is.read(buf)) != -1) {
                outStream.write(buf, 0, byteRead);
                byteWritten += byteRead;
            }
            System.out.println("Downloaded Successfully.");
            //System.out.println("File name:\"" + localFileName + "\"\nNo ofbytes :" + byteWritten);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                outStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

1 个答案:

答案 0 :(得分:2)

您可以将该代码添加到实现Runnable的类中。代码将放在方法run()中。 (您需要根据可运行的接口实现该方法。)

然后创建新线程并启动它们传递runnable。

Thread thread = new Thread(new RunnableClass());
thread.start();

您需要实现一些逻辑,以便将fAddress字符串传递给RunnableClass。 (通过构造函数,或在thread.start()之前调用的方法。)

这有助于您入门吗?

编辑 - 添加了示例

public class Main {

    public static void main(String[] args) {

        Thread thread1 = new Thread(new MyRunnable("http://someaddress"));
        thread1.start();

        Thread thread2 = new Thread(new MyRunnable("http://otheraddress"));
        thread2.start();

    }

    public static class MyRunnable implements Runnable {

        String address;

        public MyRunnable(String address) {
            this.address = address;
        }

        @Override
        public void run() {
            // My code here that can access address
        }
    }
}