पुराना सवाल है लेकिन मुझे लगता है कि आप पहले से निष्पादन() में चल रहे थ्रेड संदर्भ को कैप्चर करने के लिए ThreadPoolExecutor का विस्तार कर सकते हैं। जब shutdownNow() कहा जाएगा तो आप सभी चल रहे थ्रेड को रोक सकते हैं। हालांकि मैं आपके कार्यों में अंतर्निहित() पर भरोसा करने के लिए दृढ़ता से प्रोत्साहित करता हूं।
नमूना कोड ->
public class KillableThreadPoolExecutor extends ThreadPoolExecutor {
private final Map<Runnable, Thread> executingThreads;
public KillableThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, String threadNamePrefix) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, new YoungMemorySafeLinkedBlockingQueue<Runnable>(), ThreadFactories.create(threadNamePrefix));
executingThreads = new HashMap<>(maximumPoolSize);
}
@Override
protected synchronized void beforeExecute(Thread t, Runnable r) {
super.beforeExecute(t, r);
executingThreads.put(r, t);
}
@Override
protected synchronized void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
if(executingThreads.containsKey(r)) {
executingThreads.remove(r);
}
}
@Override
public synchronized List<Runnable> shutdownNow() {
List<Runnable> runnables = super.shutdownNow();
for(Thread t : executingThreads.values()) {
t.stop();
}
return runnables;
}
}
स्रोत
2016-10-20 16:44:00
आप 'shtudown()' या 'shutdownNow()' का उपयोग क्यों नहीं करते (या नहीं कर सकते)? ऐसा करने का यही तरीका है। – Gray
क्योंकि थ्रेड को समाप्त करने से पहले मौजूदा कार्यों को समाप्त करने की प्रतीक्षा करनी चाहिए। तो, यह तुरंत धागे को मार नहीं करता है। – deadlock
'शट डाउन() 'मौजूदा कार्यों को समाप्त करने की प्रतीक्षा करता है। यही बात है। – Gray