Thread Array Example: CS108, Stanford Handout #23 Fall, 2008-09 Osvaldo Jiménez
Thread Array Example: CS108, Stanford Handout #23 Fall, 2008-09 Osvaldo Jiménez
Here's an example that takes an array of ints and forks off multiple threads to add up all the ints in parallel.
Uses a Semaphore to notice when all the workers are done.
import java.util.*;
import java.util.concurrent.*;
/*
* This is a thread example launches multiple threads to
* sum up all the elements in an array concurrently.
* Uses worker threads and a semaphore.
*/
class ArrayThreading {
private int[] array;
private Semaphore allDone;
/***
Example command line calls:
$ java ArrayThreading 10000000 ## 10M -- fine
len:10000000 sum:45000000 workers:10
$ java ArrayThreading 100000000 ## 100M too big
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at ArrayThreading.<init>(ArrayThreading.java:16)
at ArrayThreading.main(ArrayThreading.java:92)
$ java -Xmx500m ArrayThreading 100000000 ## specify 500M memory -- fine
len:100000000 sum:450000000 workers:10
***/
public static void main(String[] args) {
// command line argument: array_length
int len = Integer.parseInt(args[0]);