Last active
March 16, 2016 11:07
-
-
Save kazurof/53a69408dc40198b0ab3 to your computer and use it in GitHub Desktop.
ズンドコキヨシをJavaで ref: http://qiita.com/kazurof/items/affd1e691e7e7a1fed1b
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.stream.Stream; | |
public class Zundoko { | |
public static void main(String args[]) { | |
StringBuilder sb = new StringBuilder(); | |
Stream<String> stream = Stream.generate(() -> Math.random() > 0.5 ? "ズン" : "ドコ"); | |
try { | |
stream.peek(s -> { | |
System.out.print(s); | |
sb.append(s); | |
if (sb.toString().endsWith("ズンズンズンズンドコ")) { | |
throw new RuntimeException(); | |
} | |
}).forEach(s -> { | |
}); | |
} catch (RuntimeException r) { | |
System.out.print("キ・ヨ・シ!"); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
public class ZundokoThread { | |
public static void main(String args[]) { | |
ExecutorService zunSer = Executors.newFixedThreadPool(1); | |
ExecutorService dokoSer = Executors.newFixedThreadPool(1); | |
ZundokoPool pool = new ZundokoPool(zunSer, dokoSer); | |
zunSer.submit(new PutTask("ズン", pool)); | |
dokoSer.submit(new PutTask("ドコ", pool)); | |
} | |
} | |
class PutTask implements Runnable { | |
String text; | |
ZundokoPool pool; | |
public PutTask(String text, ZundokoPool pool) { | |
this.text = text; | |
this.pool = pool; | |
} | |
@Override | |
public void run() { | |
while (true) { | |
try { | |
Thread.sleep((long) Math.random() * 100); | |
} catch (InterruptedException e) { | |
break; | |
} | |
pool.put(text); | |
} | |
} | |
} | |
class ZundokoPool { | |
StringBuilder sb = new StringBuilder(); | |
ExecutorService zunSer; | |
ExecutorService dokoSer; | |
public ZundokoPool(ExecutorService zunSer, ExecutorService dokoSer) { | |
this.zunSer = zunSer; | |
this.dokoSer = dokoSer; | |
} | |
synchronized void put(String str) { | |
if (Thread.currentThread().isInterrupted()) { | |
return; | |
} | |
sb.append(str); | |
// System.out.println("debug ->"+sb); | |
if (sb.toString().endsWith("ズンズンズンズンドコ")) { | |
System.out.println(sb + "キ・ヨ・シ!"); | |
zunSer.shutdownNow(); | |
dokoSer.shutdownNow(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment