working on it ...

Filters

Explore Public Snippets

Sort by

Found 263 snippets matching: multithread

    public by lbottaro  247352  3  7  0

    Lock and synchronization in python

    This example shows how to deal with lock in python parallel programming. Here we want to calculate the disk occupancy for a given directory in Linux OS, evaluating the disk occupancy for any subdirectory using threads. Note the usage of lock mechanism to ensure atomic operation on the total sum.
    import os
    import string
    import threading
    from threading import Thread
    
    disk_usage = 0
    lock = threading.Lock()
    
    for dir in os.popen('ls -d *').readlines():
        print "Dir: " + dir
        t = Thread(target=methodToBeExecutedInParallel, args=(dir,))
        t.start()
        #Join all existing threads to main thread.
        for thread in threading.enumerate():
            if thread is not threading.currentThread():
              thread.join()
        print "Disk usage = " + str(disk_usage)
    
    # Function invoked by each thread
    def methodToBeExecutedInParallel(directory):
        print "Working on dir = " + directory
        cmd = 'du -s ' + directory
        line = os.popen(cmd).readlines()[0]
        dirUsage = int(line.split()[0])
        print "Acquiring lock for "+directory+"..."
        with lock:
            print "Acquired lock for "+directory
            global disk_usage
            disk_usage += dirUsage
        print "Disk usage = " + str(dirUsage)

    public by cghersi  2687  1  6  4

    Safely Manage Asynchronous Invoke in Winforms

    When dealing with multithreading in WinForms one of the worst issues you encounter are the management of Invoke() method on controls. Instead of spreading the code of blocks if (control.InvokeRequired) { controlInvoke(...); } else { ... } this is a little method that can elegantly solve your issues!
    private delegate object SafeInvokeCallback(Control control, Delegate method, params object[] parameters);
    public static object SafeInvoke(this Control control, Delegate method, params object[] parameters)
    {
        if (control == null)
            throw new ArgumentNullException("control");
        if (control.InvokeRequired)
        {
            log.DebugFormat("Calling with BeginInvoke: {0}", method.Method.Name);
            IAsyncResult result = null;
            try { result = control.BeginInvoke(new SafeInvokeCallback(SafeInvoke), control, method, parameters); }
            catch (InvalidOperationException) { /* This control has not been created or was already (more likely) closed. */ }
            if (result != null)
                return control.EndInvoke(result);
        }
        else
        {
            log.DebugFormat("Calling sync: {0}", method.Method.Name);
            if (!control.IsDisposed)
                return method.DynamicInvoke(parameters);
        }
        return null;
    }
    

    public by lbottaro  2688  0  4  0

    Python Multithread synchronization

    How to synchronize threads in Python code. The threading module provided with Python includes a simple-to-implement locking mechanism that will allow you to synchronize threads. A new lock is created by calling the Lock() method, which returns the new lock. The acquire(blocking) method the new lock object would be used to force threads to run
    !/usr/bin/python
    
    import threading
    import time
    
    class myThread (threading.Thread):
        def __init__(self, threadID, name, counter):
            self.threadID = threadID
            self.name = name
            self.counter = counter
            threading.Thread.__init__(self)
        def run(self):
            print "Starting " + self.name
            # Get lock to synchronize threads
            threadLock.acquire()
            print_time(self.name, self.counter, 3)
            # Free lock to release next thread
            threadLock.release()
    
    def print_time(threadName, delay, counter):
        while counter:
            time.sleep(delay)
            print "%s: %s" % (threadName, time.ctime(time.time()))
            counter -= 1
    
    threadLock = threading.Lock()
    threads = []
    
    # Create new threads
    thread1 = myThread(1, "Thread-1", 1)
    thread2 = myThread(2, "Thread-2", 2)
    
    # Start new Threads
    thread1.start()
    thread2.start()
    
    # Add threads to thread list
    threads.append(thread1)
    threads.append(thread2)
    
    # Wait for all threads to complete
    for t in threads:
        t.join()
    print "Exiting Main Thread"

    public by cghersi  3408  1  6  0

    How to create an asynchronous task in C#

    This is a simple way to create a task that will run asynchronously with respect to the current thread
    System.Threading.Tasks.Task.Factory.StartNew(() =>
    {
      log.Info("This will run async");
    });
    

    public by cghersi  3198  1  6  1

    Test harness for Multithread lock management strategies

    This test suite provides a simple way to check the performances of locks vs. synchronized syntax in case of multithread safe run of a task. The parameters are added as static variable at the top of the class, MAX_LOOPS is the number of times the task is performed, and MAX_SET_SIZE is the number of simultaneous threads launched and insisting on th
    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.ArrayBlockingQueue;
    import java.util.concurrent.locks.ReentrantLock;
    
    
    public class SafeLocks {
    
    	private static int MAX_LOOPS = 1000;
    	private static int MAX_SET_SIZE = 10000;
    	
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		System.out.println("Starting ReentrantLock test bench at " + System.currentTimeMillis());
    		
    		TestSuite suite1 = new ReentrantlockEx();
    		testBench(suite1);
    		
    		System.out.println("Starting Synchronized test bench at " + System.currentTimeMillis());
    		
    		TestSuite suite2 = new SynchronizedEx();
    		testBench(suite2);
    
    		System.out.println("END");
    	}
    	
    	private static void testBench(final TestSuite test) {
    		for (int thIdx = 0; thIdx < MAX_SET_SIZE; thIdx++) {
    			Thread t = new Thread(new Runnable() {			
    				@Override
    				public void run() {
    					long summedSpentTime = 0;
    					for (int i = 0; i < MAX_LOOPS; i++) {
    						long startTime = System.currentTimeMillis();
    						test.doStuff(i);
    						summedSpentTime += (System.currentTimeMillis() - startTime);
    					}
    					test.addTime(summedSpentTime);
    				}
    			});
    			t.start();
    		}
    		
    		while (test.threadsFinished() < MAX_SET_SIZE) {
    			try {
    				Thread.sleep(2000);
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    		}
    		
    		List<Long> times = test.getTimes();
    		long totalTime = 0;
    		for (long l : times) {
    			totalTime += l;
    		}
    		System.out.println("Suite finished: # of threads: " + MAX_SET_SIZE + "; # of running cycles of single task: " + 
    				MAX_LOOPS + "; avg time is " + (totalTime / times.size()));
    	}
    	
    	public static abstract class TestSuiteImpl implements TestSuite {
    
    		private ArrayBlockingQueue<Long> runTimes = new ArrayBlockingQueue<Long>(MAX_SET_SIZE + 1);
    
    		public void addTime(long time) {
    			runTimes.add(time);
    		}
    		
    		public List<Long> getTimes() {
    			List<Long> res = new ArrayList<>();
    			runTimes.drainTo(res);
    			return res;
    		}
    		
    		public int threadsFinished() {
    			return runTimes.size();
    		}
    	}
    	
    	public static class ReentrantlockEx extends TestSuiteImpl implements TestSuite {
    		private ReentrantLock lock = new ReentrantLock();
    
    		public final boolean doStuff(int number) {
    			boolean result = false;
    			lock.lock();
    			
    			//do something not completely stupid so that compiler will not get rid of it
    			String test = "abc0";
    			result = (test.hashCode() == number);
    			
    			lock.unlock();
    			return result;
    		}
    	}
    	
    	public static class SynchronizedEx extends TestSuiteImpl implements TestSuite {
    		
    		private final Object syncObj = new Object();
    
    		public final boolean doStuff(int number) {
    			boolean result = false;
    			synchronized (syncObj) {
    				//do something not completely stupid so that compiler will not get rid of it
    				String test = "abc0";
    				result = (test.hashCode() == number);
    			}
    			return result;
    		}
    	}
    	
    	public static interface TestSuite {
    		public boolean doStuff(int number);
    		public void addTime(long time);
    		public List<Long> getTimes();
    		public int threadsFinished();
    	}
    
    }

    public by cghersi  2769  1  6  2

    Safe Realization of a Thread in Java

    Manage threads in Java can be tricky, most of all the stop of them. With this class no littering thread will be left behind.
    import java.lang.Thread;
    import java.util.List;
    
    public class MySafeThread implements Runnable {
    
    	private static MySafeThread singleton = null;
    	/**
    	 * Synchronization variable for the safe instantiation of the singleton
    	 */
    	private static Object synchSingleton = new Object();
    	/**
    	 * The actual thread object
    	 */
    	private Thread thread;
    	/**
    	 * The flag signalling whether the thread is running or not
    	 */
    	private boolean threadRunning = false;
    
    	
    	private MySafeThread(){
    	}
    
    	public void restart() {
    		closeThread();
    		startThread();
    	}
    
    
    	/**
    	 * Closes the thread, releasing all the resources
    	 */
    	public void closeThread(){
    		threadRunning = false;
    
    		//break the execution of the thread and wait until the last loop is finished:
    		Thread moribond = this.thread;
    		this.thread=null;
    		moribond.interrupt();
    
    		singleton = null;
    	}
    
    	
    	/**
    	 * Retrieves the singleton instance of the class; if
    	 * the singleton has not yet been instantiated, it builds 
    	 * a new instance using the protected constructor.
    	 * @return The singleton instance of the class
    	 */
    	public static MySafeThread get(){
    		if (singleton == null) {
    			synchronized (synchSingleton) {
    				if (singleton == null) {
    					singleton = new MySafeThread();
    				}
    			}
    		}
    	
    		return singleton;
    	}
    
    	/**
    	 * The main method of the thread which listens for new responses available, and
    	 * sends them via IPC
    	 */
    	public void run(){
    		Thread t = Thread.currentThread();
    		
    		threadRunning = true;
    		while(threadRunning) {
    			//do something...
    		}
    	}
    
    	/**
    	 * Starts the thread
    	 */
    	public void startThread(){
    		//only a single instance of the thread can run:
    		if (threadRunning)
    			return;
    	
    		this.thread = new Thread(this, "GiveANameToTheThread");
    		this.thread.start();	
    	}
    }

    public by cghersi  2789  2  7  1

    Manage a queue in Java

    This simple class has a queue that is filled and depleted with its two methods. The getter blocks until a new item is ready on the queue. It can be used also as a synchronization mechanism between two threads
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Observable;
    import java.util.Observer;
    import java.util.concurrent.ArrayBlockingQueue;
    import java.util.concurrent.ConcurrentHashMap;
    
    public class ClassWithQueue {
    
    	private ArrayBlockingQueue<String> incomingTextMessages;
    	
    	public StubIPCJ(){
    		incomingTextMessages = new ArrayBlockingQueue<String>(1000);
    	}
    	
    	public String getTextMessage(){
    		String msg = null;
    		try {			
    			msg = incomingTextMessages.take();
    		} catch (InterruptedException e) {
    			log.error("ipcGetFrame failure: " + e.getMessage());
    			return null;
    		}
    			
    		return msg; 		
    	}
    
    	public void addToQueue(String obj) {		
    		synchronized(incomingTextMessages){
    			try {
    				incomingTextMessages.add(obj);
    			}catch(IllegalStateException ew){
    				incomingTextMessages.poll();
    				incomingTextMessages.add(obj);
    			}
    		}								
    	}
    }
    

    public by sTiLL-iLL  2992  1  6  10

    ParaFunc.cs - Parallelized Functional stuffs : Sort, Search, Map, Reduce, MapReduce

    It hardly blows anything up! LoL an experiment in functional programming
    using System;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    
    
    namespace ParaStuff
    {
    
        public class ParallelSort<T>
        {
    
            public static void ParaQuickSort (T[] data, IComparer<T> comp, int limit = 16, int minSize = 10000)
            {
                DoSort(data, 0, data.Length - 1, comp, 0, limit, minSize);
            }
    
    
            internal static void DoSort (T[] data, int start, int end, IComparer<T> comp, int curIdx, int limit, int minSize)
            {
                if (start < end)
                {
                    if (curIdx > limit || end - start < minSize)
                    {
                        Array.Sort(data, start, end - start + 1, comp);
                    }
                    else
                    {
                        int pivotAt = Sector(data, start, end, comp);
                        Task lTsk = Task.Factory.StartNew(( ) => {
                            DoSort(data, start, pivotAt - 1, comp, curIdx + 1, limit, minSize);
                        });
                        Task rTsk = Task.Factory.StartNew(( ) => {
                            DoSort(data, pivotAt + 1, end, comp, curIdx + 1, limit, minSize);
                        });
    
                        Task.WaitAll(lTsk, rTsk);
                    }
                }
            }
            
            internal static void Switch (T[] data, int firstIdx, int secondIdx)
            {
                T pxy = data[firstIdx];
                data[firstIdx] = data[secondIdx];
                data[secondIdx] = pxy;
            }
    
            internal static int Sector (T[] data, int start, int end, IComparer<T> comp)
            {
                // get the pivot and put it at the end
                T pivot = data[start];
                Switch(data, start, end);
                int saveAt = start;
    
                for (int i = start; i < end; i++)
                {
                    if (comp.Compare(data[i], pivot) <= 0)
                    {
                        Switch(data, i, saveAt);
                        saveAt++;
                    }
                }
    
                Switch(data, saveAt, end);
                return saveAt;
            }
        }
    
    
        public class Graph<T>
        {
            public Graph<T> LeftNd, RightNd;
            public T Data;
        }
    
    
        public class GraphSeeker
        {
            public static void Seek<T> (Graph<T> grph, Action<T> actn)
            {
                if (grph != null)
                {
                    actn.Invoke(grph.Data);
                    if (grph.LeftNd != null && grph.RightNd != null)
                    {
                        Task lTsk = Task.Factory.StartNew(( ) => Seek(grph.LeftNd, actn));
                        Task rTsk = Task.Factory.StartNew(( ) => Seek(grph.RightNd, actn));
                        Task.WaitAll(lTsk, rTsk);
                    }
                }
            }
        }
    
    
        public class GraphSearch
        {
            private static CancellationTokenSource tokSrc;
    
            public static T Search<T> (Graph<T> grph, Func<T, bool> searchFunc)
            {
    
                tokSrc = new CancellationTokenSource();
                GraphWrap<T> rzlt = Search(grph, searchFunc, tokSrc);
                return rzlt == null ? default(T) : rzlt.Value;
            }
    
            public class GraphWrap<T>
            {
                public T Value;
            }
    
    
            private static GraphWrap<T> Search<T> (Graph<T> grph, Func<T, bool> searchFunc, CancellationTokenSource tokSrc)
            {
                GraphWrap<T> rzlt = null;
    
                if (grph != null)
                {
                    if (searchFunc(grph.Data))
                    {
                        tokSrc.Cancel();
                        rzlt = new GraphWrap<T>()
                        {
                            Value = grph.Data
                        };
                    }
                    else
                    {
                        if (grph.LeftNode != null && grph.RightNode != null)
                        {
                            Task<GraphWrap<T>> lTsk = Task<GraphWrap<T>>.Factory.StartNew(( ) => Search(grph.LeftNode, searchFunc, tokSrc), tokSrc.Token);
                            Task<GraphWrap<T>> rTsk = Task<GraphWrap<T>>.Factory.StartNew(( ) => Search(grph.RightNode, searchFunc, tokSrc), tokSrc.Token);
                            try
                            {
                                rzlt = lTsk.Result != null ? lTsk.Result : rTsk.Result != null ? rTsk.Result : null;
                            }
                            catch (Exception)
                            {       }
                        }
                    }
                }
    
                return rzlt;
            }
        }
    
    
        public class ParallelCache<TKey, TValue>
        {
            private ConcurrentDictionary<TKey, Lazy<TValue>> catalog;
            private Func<TKey, TValue> factory;
    
            public ParallelCache (Func<TKey, TValue> fac)
            {
                factory = fac;
                catalog = new ConcurrentDictionary<TKey, Lazy<TValue>>();
            }
    
            public TValue GetCurrentVal (TKey k)
            {
                return catalog.GetOrAdd(k, new Lazy<TValue>(( ) => factory(k))).Value;
            }
        }
    
    
        public class ParaMap
        {
            public static TOutput[] PMap<TInput, TOutput> (Func<TInput, TOutput> mapFunc, TInput[] data)
            {
                return data.AsParallel().AsOrdered().Select(value => mapFunc(value)).ToArray();
            }
        }
    
    
        public class ParaReduce
        {
            public static TValue PReduce<TValue> (TValue[] src, TValue seed, Func<TValue, TValue, TValue> reduceFunc)
            {
                return src.AsParallel().Aggregate(seed, (lRzlt, val) => reduceFunc(lRzlt, val), (oRzlt, lRzlt) => reduceFunc(oRzlt, lRzlt), oRzlt => oRzlt);
            }
        }
    
    
        public class ParaMapReduce
        {
            public static IEnumerable<TOutput> PMapReduce<TInput, TIntermediate, TKey, TOutput> (IEnumerable<TInput> src, Func<TInput, IEnumerable<TIntermediate>> mapFunc, Func<TIntermediate, TKey> groupFunc, Func<IGrouping<TKey, TIntermediate>, TOutput> reduceFunc)
            {
                return src.AsParallel().SelectMany(mapFunc).GroupBy(groupFunc).Select(reduceFunc);
            }
        }
    
    
        public static class SmartSelection
        {
            public static void Calculate<TInput, TOutput> (TInput value, Action<long, TOutput> callback, params Func<TInput, TOutput>[] functions)
            {
                int cnt= 0;
                Task.Factory.StartNew(( ) => {
                  Parallel.ForEach(functions, (Func<TInput, TOutput> func, ParallelLoopState lpSt, long idx) => {
                        TOutput rez = func(value);
                        if (Interlocked.Increment(ref cnt) == 1)
                        {
                            lpSt.Stop();
                            callback(idx, rez);
                        }
                    });
                });
            }
        }
    
    
        public class SmartCache<TKey, TValue>
        {
            private ConcurrentDictionary<TKey, Lazy<TValue>> catalog;
            private BlockingCollection<TKey> roster;
            private Func<TKey, TKey[]> smartFunc;
            private Func<TKey, TValue> facFunc;
    
            public SmartCache (Func<TKey, TValue> factory, Func<TKey, TKey[]> spec)
            {
                smartFunc = spec;
                catalog = new ConcurrentDictionary<TKey, Lazy<TValue>>();
                roster = new BlockingCollection<TKey>();
    
                facFunc = (k => {
                    TValue value = factory(k);
                    roster.Add(k);
    
                    return value;
                });
    
                Task.Factory.StartNew(( ) => {
                    Parallel.ForEach(roster.GetConsumingEnumerable(),
                        new ParallelOptions
                        {
                            MaxDegreeOfParallelism = 2
                        },
                        k => {
                            // ya gotta enumerate to speculate! 
                            foreach (TKey spk in smartFunc(k))
                            {
                                TValue res = catalog.GetOrAdd(spk, new Lazy<TValue>(( ) => factory(spk))).Value;
                            }
                        });
                });
            }
    
            public TValue GetCurrentVal (TKey k)
            {
                return catalog.GetOrAdd(k, new Lazy<TValue>(( ) => facFunc(k))).Value;
            }
        }
    }
    
    
    
    namespace ParaStuff.FeedBackWindow
    {
      
      // use this specialized console for any output etc. that you need
      
        public class FeedBackWindow
        {
            private static BlockingCollection<Action> bq;
            private static Task msgThd;
    
    
            static FeedBackWindow ( )
            {
                bq = new BlockingCollection<Action>();
                msgThd = Task.Factory.StartNew(( ) =>
                {
                    foreach (Action atn in bq.GetConsumingEnumerable())
                    {
                        atn.Invoke();
                    }
                }, TaskCreationOptions.LongRunning);
            }
    
    
            public static void WriteLine (object val)
            {
                bq.Add(new Action(( ) => Console.WriteLine(val)));
            }
    
    
            public static void WriteLine (string fmt, params object[] vals)
            {
                bq.Add(new Action(( ) => Console.WriteLine(fmt, vals)));
            }
        }
    }
    
    
    namespace ParaStuff.Pipeline
    {
      
        private class Reaction
        {
            public TInput Value;
            public Action<TInput, TOutput> Callback;
        }
      
      
        public class Pipeline<TInput, TOutput>
        {
            private BlockingCollection<Reaction> valQ;
            Func<TInput, TOutput> pipelineFunc;
    
            public Pipeline (Func<TInput, TOutput> func)
            {
                pipelineFunc = func;
            }
    
            public Pipeline<TInput, TNewOutput> AddFunction<TNewOutput> (Func<TOutput, TNewOutput> newfunc)
            {
                Func<TInput, TNewOutput> frankenFunc = (dta =>
                {
                    return newfunc(pipelineFunc(dta));
                });
                return new Pipeline<TInput, TNewOutput>(frankenFunc);
            }
    
            public void AddVal (TInput val, Action<TInput, TOutput> callback)
            {
                valQ.Add(new Reaction
                {
                    Value = val,
                    Callback = callback
                });
            }
    
            public void Begin ( )
            {
                valQ = new BlockingCollection<Reaction>();
                Task.Factory.StartNew(( ) =>
                {
                    Parallel.ForEach(valQ.GetConsumingEnumerable(), rpr =>
                    {
                        rpr.Callback(rpr.Value, pipelineFunc(rpr.Value));
                    });
                });
            }
    
            public void End ( )
            {
                valQ.CompleteAdding();
            }
        }
    }
    
    
                

    public by cghersi  2583  0  7  2

    safe use of locks in Java

    This class shows how to safely implement a lock to manage a crucial variable, accessed by several threads in concurrency. Just a notes on the use of ReentrantLock: its use may be replaced by a simple synchronized block where no huge concurrency issues are forecasted (say, less than 700 concurrent threads)
    import java.util.concurrent.locks.ReentrantLock;
    
    public abstract class LockedClass {
    
    	/**
    	 * Determines whether or not a call (i.e. a particular method of the class)
    	 * should be always sent, without depending from the implementation 
    	 * of isChildSendable() in the children classes
    	 */
    	private boolean isAlwaysSendable = true;
    	/**
    	 * Lock for the guard of sending mechanism.
    	 */
    	private ReentrantLock lock = new ReentrantLock();
    	
    	public LockedClass(boolean isAlwaysendable) {
    	  this.isAlwaysendable = isAlwaysendable;
    	}
    
    	protected boolean isChildSendable(){
    	  //override this behavior in children classes if you need...
    		return true;
    	}
    
    	public final boolean isSendable(){
    		if (isAlwaysSendable)
    			return true;
    		
    		boolean b;
    		lock.lock();
    		b = isChildSendable();
    		if (b)
    			setChildSendable(false);
    		lock.unlock();
    		return b;
    	}
    
    	protected void setChildSendable(boolean sendable){
    	  //put something here or override in children classes if you want to 
    	  //customize
    	}
    
    	public final void setSendable(boolean sendable){
    		if (isAlwaysSendable)
    			return;
    		
    		lock.lock();
    		setChildSendable(sendable);
    		lock.unlock();
    	}
    }

    public by lbottaro  6101  4  8  6

    Asynchronous processing using Future and Callable java interfaces

    Java Future and Callable interfaces allow to easily manage asynchronous run and elaboration for long time-consuming operations. Each MyCallableObject implements Callable interface, specifying the behavior of call() method. In this example, ExecutorService will execute the MyCallableObject processing routine using a pool of configurable threads, i
    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    
    public class CallableFutureTest {
    	private static final int NTHREDS = 5;
    
    	public static void main(String[] args) {
    
    		ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
    		List<Future<Long>> list = new ArrayList<Future<Long>>();
    		for (int i = 0; i < 100; i++) {
    			Callable<Long> worker = new MyCallableObject();
    			Future<Long> submit = executor.submit(worker);
    			list.add(submit);
    			System.out.println("Added future " + submit.toString());
    
    		}
    		long sum = 0;
    		try {
    			Thread.sleep(10000);
    		} catch (InterruptedException e1) {
    			// TODO Auto-generated catch block
    			e1.printStackTrace();
    		}
    		System.out.println(list.size());
    
    		// now retrieve the result
    		for (Future<Long> future : list) {
    			try {
    				System.out.println("Current future " + future.toString());
    				System.out.println("Future before get is " + future.isDone());
    				sum += future.get();
    				System.out.println("Future after get is " + future.isDone());
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			} catch (ExecutionException e) {
    				e.printStackTrace();
    			}
    		}
    		System.out.println(sum);
    		executor.shutdown();
    	}
    }
    • Public Snippets
    • Channels Snippets