Skip to content

Instantly share code, notes, and snippets.

@neojou
Created March 30, 2015 18:12
Show Gist options
  • Save neojou/b8fe7cb171d9f98a4126 to your computer and use it in GitHub Desktop.
Save neojou/b8fe7cb171d9f98a4126 to your computer and use it in GitHub Desktop.
Java : Thread / callable example : to find out the max integer
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package neo.util;
import java.util.concurrent.Callable;
/**
*
* @author neojou
*/
class FindMaxTask implements Callable<Integer> {
private int data[];
private int start;
private int end;
FindMaxTask(int data[], int start, int end) {
this.data = data;
this.start = start;
this.end = end;
}
public Integer call() {
int max = Integer.MIN_VALUE;
for (int i=start; i<end; i++) {
if (data[i]>max) max = data[i];
}
return max;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package neo.util;
import java.util.concurrent.*;
/**
*
* @author neojou
*/
public class MultiThreadMaxFinder {
public static int max(int[] data) throws InterruptedException, ExecutionException {
if ( data.length == 1 ) return data[0];
else if ( data.length == 0 ) throw new IllegalArgumentException();
FindMaxTask task1 = new FindMaxTask(data, 0, data.length/2);
FindMaxTask task2 = new FindMaxTask(data, data.length/2, data.length);
ExecutorService service = Executors.newFixedThreadPool(2);
Future<Integer> future1 = service.submit(task1);
Future<Integer> future2 = service.submit(task2);
return Math.max(future1.get(), future2.get());
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int[] a = { 1, 10, 2, 3, 5, 8, 4, 6, 9 };
for (int i=0; i<a.length; i++)
System.out.println(a[i]);
System.out.print("Max number:");
try {
System.out.println(MultiThreadMaxFinder.max(a));
} catch ( Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment