Skip to content

Instantly share code, notes, and snippets.

@kamatama41
Created March 6, 2013 13:53
Show Gist options
  • Save kamatama41/5099442 to your computer and use it in GitHub Desktop.
Save kamatama41/5099442 to your computer and use it in GitHub Desktop.
MultiThreadFizzBuzz
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
* User: kamatama_41
*/
public class MultiThreadFizzBuzz {
// 伝送路役のQueue
private static BlockingQueue<Integer> densoro = new ArrayBlockingQueue<Integer>(100);
// Producerが提供が終わったかどうかのフラグ
private static volatile boolean finished = false;
public static void main(String[] args) throws Exception{
execute(Consumer.class, 3, 250L);
execute(Producer.class, 3, 250L);
// execute2(Consumer.class, 3, 250L);
// execute2(Producer.class, 3, 250L);
}
private static void execute(Class<? extends Thread> threadClass, int threadSize, long intervalMills) throws Exception{
for(int i = 0; i < threadSize; i++) {
Thread thread = threadClass.getConstructor(long.class).newInstance(intervalMills);
thread.start();
}
}
private static void execute2(Class<? extends Thread> threadClass, int threadSize, long intervalMills) throws Exception {
Collection<Future> result = new ArrayList<Future>(threadSize);
ExecutorService threadPoolExecutor = Executors.newFixedThreadPool(threadSize);
for(int i = 0; i < threadSize; i++) {
result.add(threadPoolExecutor.submit(threadClass.getConstructor(long.class).newInstance(intervalMills)));
}
threadPoolExecutor.shutdown();
}
public static class Producer extends Thread {
private static final AtomicInteger counter = new AtomicInteger();
private long intervalMills;
public Producer(long intervalMills) { this.intervalMills = intervalMills; }
@Override
public void run() {
try {
while(counter.get() < 100) {
densoro.offer(counter.incrementAndGet());
TimeUnit.MILLISECONDS.sleep(intervalMills);
}
finished = true;
} catch (Exception e) {
}
}
}
public static class Consumer extends Thread {
private long intervalMills;
public Consumer(long intervalMills) { this.intervalMills = intervalMills; }
@Override
public void run() {
try {
while(!finished) {
System.out.println(fizzBuzz(densoro.take()));
TimeUnit.MILLISECONDS.sleep(intervalMills);
}
} catch (Exception e) {
}
}
private static String fizzBuzz(int count) {
if(count % 15 == 0) {
return "FizzBuzz," + count;
} else if(count % 3 == 0) {
return "Fizz," + count;
} else if(count % 5 == 0) {
return "Buzz," + count;
} else {
return String.valueOf(count);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment