Created
November 7, 2017 21:19
-
-
Save rokon12/4e80948e96252b4ae2095c0494a58764 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package thread; | |
import java.io.*; | |
import java.net.URL; | |
import java.net.URLConnection; | |
import java.nio.file.Files; | |
import java.nio.file.StandardCopyOption; | |
class DownloadingHeartBeat extends Thread { | |
private volatile boolean beating = true; | |
@Override | |
public void run() { | |
String[] dots = { | |
".", | |
"..", | |
"...", | |
"...." | |
}; | |
while (beating) { | |
for (String dot : dots) { | |
System.out.print("\r" + dot); | |
try { | |
Thread.sleep(50); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
public void shutdown() { | |
this.beating = false; | |
} | |
} | |
class FileDownloader extends Thread { | |
private String url; | |
private String fileName; | |
public FileDownloader(String url, String fileName) { | |
this.url = url; | |
this.fileName = fileName; | |
} | |
@Override | |
public void run() { | |
try { | |
System.out.println("Started to download '" + fileName + "'"); | |
URL resourceToDownload = new URL(url); | |
URLConnection connection = resourceToDownload.openConnection(); | |
InputStream input = connection.getInputStream(); | |
File fileToSave = new File(fileName); | |
Files.copy(input, fileToSave.toPath(), StandardCopyOption.REPLACE_EXISTING); | |
input.close(); | |
} catch (IOException e) { | |
System.err.println("Couldn't download the file: " + e.getMessage()); | |
} | |
} | |
} | |
public class ThreadJoinExample { | |
public static void main(String[] args) throws InterruptedException { | |
FileDownloader downloader1 | |
= new FileDownloader("https://secure.meetupstatic.com/photos/event/e/9/f/9/600_464039897.jpeg", "jugbd-meetup7_1.jpeg"); | |
FileDownloader downloader2 | |
= new FileDownloader("https://secure.meetupstatic.com/photos/event/2/d/0/f/600_464651535.jpeg", "jugbd-meetup7_2.jpeg"); | |
DownloadingHeartBeat heartBeat = new DownloadingHeartBeat(); | |
downloader1.start(); | |
downloader2.start(); | |
heartBeat.start(); | |
try { | |
downloader1.join(); | |
downloader2.join(); | |
//both threads are done, lets shutdown the heartbeat | |
heartBeat.shutdown(); | |
// lets wait for stopping the heartbeat thread | |
heartBeat.join(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
System.out.println("\nThe download is complete"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment