Last active
January 23, 2016 20:42
-
-
Save kishida/d375010dc108d6e383ca to your computer and use it in GitHub Desktop.
Multi thread but resource is conflict.
This file contains hidden or 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 ThreadMulti { | |
static class Context{ | |
String str; | |
int i = 0; | |
boolean inParenthesis = false; | |
boolean terminated = false; | |
Context(String str){ | |
this.str = str; | |
} | |
} | |
public static void main(String[] args) { | |
StringBuilder sb = new StringBuilder(); | |
Context[] ctxs = { | |
new Context("abc(def)gh(ijk)lmn"), | |
new Context("(abc)def(gh)ijk(lmn)")}; | |
int ctxId = 0; | |
while(Stream.of(ctxs).anyMatch(c -> !c.terminated)){ | |
Context ctx = ctxs[ctxId]; | |
ctxId = (ctxId + 1) % ctxs.length; | |
if(ctx.terminated){ | |
continue; | |
} | |
if(ctx.i >= ctx.str.length()){ | |
ctx.terminated = true; | |
continue; | |
} | |
char ch = ctx.str.charAt(ctx.i); | |
switch(ch){ | |
case '(': | |
ctx.inParenthesis = true; | |
break; | |
case ')': | |
ctx.inParenthesis = false; | |
break; | |
default: | |
if(ctx.inParenthesis){ | |
sb.append(ch); | |
} | |
} | |
++ctx.i; | |
} | |
System.out.println(sb); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment