简体   繁体   中英

executor service in java for multi threading, ignore the details of threading?

I tried learning threads and runnable in java and a collegue of mine told me to stop it will take too learn these details. Just lookup how to write an executor. How does this work in java. Can someone provide an example?

Thank you!

To solve small, isolated problems in programming without a bigger project behind, you can go and learn about executors directly. Here is an example of how to use Threads pools with the Executor Framework , which is suitable as an entry point.

However, if you plan to work more in an environment where concurrency is an important topic, then it is crucial to have a profound understanding of the basics behind more high level concepts. With a good understanding of what happens behind the scenes, you will be able to judge quickly what the best solution is for a problem in regard to performance and scalability. Without this understanding, the code you write will do what you want it to do, but if it gets applied to slightly different scenarios that you didn't test, it is likely that your code will perform poorly, maybe even be unusable because of performance degredation. Concurrency is a complex topic and the concepts for solutions can't be applied well without good understanding of the matter.

Having said this, I strongly recommend also learning about Threads and Runnable.

This is an easy to understand implementation of an executor that will run three classes together at max:

ExecutorService executorService = Executors.newFixedThreadPool(3);
Callable<Void> thread1 = new MyClass(); 
executorService.submit(thread1);
Callable<Void> thread2 = new MyClass2(); 
executorService.submit(thread2);                
executorService.shutdown();

and the class:

public class MyClass implements Callable<Void> {
@Override
public Void call() throws Exception{ }
}

It is true you don't need in depth knowledge for basic stuff just keep in mind that if your classes are accessing shared resources with the possibility of conflicts then you need to have a proper thread implementation with locking etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM