001 /* 002 * Copyright (C) 2008-2010 by Holger Arndt 003 * 004 * This file is part of the Universal Java Matrix Package (UJMP). 005 * See the NOTICE file distributed with this work for additional 006 * information regarding copyright ownership and licensing. 007 * 008 * UJMP is free software; you can redistribute it and/or modify 009 * it under the terms of the GNU Lesser General Public License as 010 * published by the Free Software Foundation; either version 2 011 * of the License, or (at your option) any later version. 012 * 013 * UJMP is distributed in the hope that it will be useful, 014 * but WITHOUT ANY WARRANTY; without even the implied warranty of 015 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 016 * GNU Lesser General Public License for more details. 017 * 018 * You should have received a copy of the GNU Lesser General Public 019 * License along with UJMP; if not, write to the 020 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, 021 * Boston, MA 02110-1301 USA 022 */ 023 024 package org.ujmp.core.util.concurrent; 025 026 import java.util.concurrent.Callable; 027 import java.util.concurrent.Future; 028 import java.util.concurrent.ThreadPoolExecutor; 029 030 import org.ujmp.core.util.UJMPSettings; 031 032 public abstract class PForEquidistant { 033 034 private final Object[] objects; 035 036 public PForEquidistant(final int threads, final int first, final int last, 037 final Object... objects) { 038 this.objects = objects; 039 040 if (threads < 2) { 041 for (int i = first; i <= last; i++) { 042 step(i); 043 } 044 } else { 045 final ThreadPoolExecutor es = UJMPThreadPoolExecutor.getInstance(threads); 046 047 final Future<?>[] list = new Future[threads]; 048 049 for (int i = 0; i < threads; i++) { 050 list[i] = es.submit(new StepCallable(first + i, last, threads)); 051 } 052 053 for (Future<?> f : list) { 054 try { 055 f.get(); 056 } catch (Exception e) { 057 e.printStackTrace(); 058 } 059 } 060 } 061 } 062 063 public PForEquidistant(final int first, final int last, final Object... objects) { 064 this(UJMPSettings.getNumberOfThreads(), first, last, objects); 065 } 066 067 public abstract void step(final int i); 068 069 public final Object getObject(final int i) { 070 return objects[i]; 071 } 072 073 class StepCallable implements Callable<Object> { 074 private final int first; 075 private final int last; 076 private final int stepsize; 077 078 public StepCallable(final int first, final int last, final int stepsize) { 079 this.first = first; 080 this.last = last; 081 this.stepsize = stepsize; 082 } 083 084 public final Void call() throws Exception { 085 try { 086 for (int i = first; i <= last; i += stepsize) { 087 step(i); 088 } 089 } catch (Exception e) { 090 e.printStackTrace(); 091 } 092 return null; 093 } 094 095 } 096 097 }