Home Ask Login Register

Developers Planet

Your answer is one click away!

J. Doe February 2016

How to do multiple tasks at once?

How could I make this download 2 to 3 files at once and when 1 finishes it picks up another? Right now it does what it needs to do, but it takes a while if you're downloading like 30 videos at once, so I want it to download 2 or 3 at a time.

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) {
        } finally {
            try {
            } catch (IOException e) {


jheimbouch February 2016

You could add that code to a class that implements Runnable. The code would go in the method run(). (You need to implement that method per the runnable interface.)

You then create new threads and start them passing your runnable.

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

You'll need to implement some logic for passing the fAddress String to the RunnableClass. (Via the constructor, or a method that gets called before thread.start().)

Does this help you get started?

EDIT - Added example

public class Main {

    public static void main(String[] args) {

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

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


    public static class MyRunnable implements Runnable {

        String address;

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

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

Post Status

Asked in February 2016
Viewed 2,482 times
Voted 5
Answered 1 times


Leave an answer

Quote of the day: live life