मैं exectorServices
का उपयोग threads
पूल करने और कार्यों को भेजने के लिए सीख रहा हूं। मैं नीचेअंतर?
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
class Processor implements Runnable {
private int id;
public Processor(int id) {
this.id = id;
}
public void run() {
System.out.println("Starting: " + id);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("sorry, being interupted, good bye!");
System.out.println("Interrupted "+Thread.currentThread().getName());
e.printStackTrace();
}
System.out.println("Completed: " + id);
}
}
public class ExecutorExample {
public static void main(String[] args) {
Boolean isCompleted=false;
ExecutorService executor = Executors.newFixedThreadPool(2);
for(int i=0; i<5; i++) {
executor.execute(new Processor(i));
}
//executor does not accept any more tasks but the submitted tasks continue
executor.shutdown();
System.out.println("All tasks submitted.");
try {
//wait for the exectutor to terminate normally, which will return true
//if timeout happens, returns false, but this does NOT interrupt the threads
isCompleted=executor.awaitTermination(100, TimeUnit.SECONDS);
//this will interrupt thread it manages. catch the interrupted exception in the threads
//If not, threads will run forever and executor will never be able to shutdown.
executor.shutdownNow();
} catch (InterruptedException e) {
}
if (isCompleted){
System.out.println("All tasks completed.");
}
else {
System.out.println("Timeout "+Thread.currentThread().getName());
}
}
}
एक सरल कार्यक्रम है यह कल्पना कुछ नहीं करता है, लेकिन दो threads
बनाता है और कुल 5 कार्य सबमिट करता है। प्रत्येक thread
अपने कार्य को पूरा करने के बाद, यह अगले एक, ऊपर दिए गए कोड में, मैं executor.submit
का उपयोग करता हूं। मैं भी executor.execute
में बदल गया। लेकिन मुझे आउटपुट में कोई अंतर नहीं दिख रहा है। submit and execute
विधियों किस तरह से भिन्न हैं? यह वही है API
कहते
विधि प्रस्तुत फैली बनाने और भविष्य कि निष्पादन रद्द करने और/या पूरा करने के लिए प्रतीक्षा करने के लिए इस्तेमाल किया जा सकता वापस लौट कर आधार विधि Executor.execute (java.lang.Runnable)। विधियों का आह्वान करें किसी भी और invoke सभी कार्यों के संग्रह को निष्पादित करने, और कम से कम एक, या सभी के लिए इंतजार कर, थोक निष्पादन के सबसे आम रूपों का प्रदर्शन करते हैं। (क्लास एक्जिक्यूटर कॉम्प्लिशन सेवा का उपयोग इन विधियों के कस्टमाइज्ड वेरिएंट लिखने के लिए किया जा सकता है।)
लेकिन यह मेरे लिए स्पष्ट नहीं है कि इसका क्या अर्थ है? धन्यवाद
उपयोगी सवाल। इसे यहां पोस्ट करने का मूल्य है। – MKod