How to run two methods simultaneously

I have this piece of code:

public static void main(String[] args) { Downoader down = new Downoader(); Downoader down2 = new Downoader(); down.downloadFromConstructedUrl("http:xxxxx", new File("./references/word.txt"), new File("./references/words.txt")); down2.downloadFromConstructedUrl("http:xxxx", new File("./references/word1.txt"), new File("./references/words1.txt")); System.exit(0); } 

Is it possible to run these two methods: down.downloadFromConstructedUrl() and down2.downloadFromConstructedUrl() at the same time? If so, how?

+4
source share
7 answers

You start two threads:

Try the following:

 // Create two threads: Thread thread1 = new Thread() { public void run() { new Downloader().downloadFromConstructedUrl("http:xxxxx", new File("./references/word.txt"), new File("./references/words.txt")); } }; Thread thread2 = new Thread() { public void run() { new Downloader().downloadFromConstructedUrl("http:xxxxx", new File("./references/word1.txt"), new File("./references/words1.txt")); } }; // Start the downloads. thread1.start(); thread2.start(); // Wait for them both to finish thread1.join(); thread2.join(); // Continue the execution... 

(You may need to add a few try / catch blocks, but the code above should give you a good start.)

Further reading:

+11
source

You can use Thread and run both methods in parallel using multithreading. You will have to override run() and call Thread.start()

Please note that you will have to take care of synchronizing your methods.

Also note: you will get a “real parallel launch” only if your computer has 2+ kernels, however if it is not, the OS will simulate a “parallel” launch for you.

+3
source

Instead of using threads directly, it’s better to use an ExecutorService and run all download tasks through this service. Sort of:

 ExecutorService service = Executors.newCachedThreadPool(); Downloader down = new Downloader("http:xxxxx", new File("./references/word.txt"), new File("./references/words.txt")); Downloader down2 = new Downloader("http:xxxx", new File("./references/word1.txt"), new File("./references/words1.txt")); service.invokeAll(Arrays.asList(down, down2)); 

In your Downloader class, the Callable interface should be implemented.

+3
source

What are threads for? A thread is a lightweight internal process used to run code in parallel with your "main thread".

http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html

0
source

This will be what concurrency and threading for.

0
source

You start two different threads, but they will work really in parallel if you have at least a 2-core machine. Multithreading Google Java.

0
source

Yes, it is absolutely possible. However, multithreaded or parallel programming is a very broad and complex topic.

Best to start here.

http://docs.oracle.com/javase/tutorial/essential/concurrency/

0
source

Source: https://habr.com/ru/post/1400955/


All Articles