Skip to content

Instantly share code, notes, and snippets.

@kishida
Last active January 23, 2016 20:42
Show Gist options
  • Save kishida/d375010dc108d6e383ca to your computer and use it in GitHub Desktop.
Save kishida/d375010dc108d6e383ca to your computer and use it in GitHub Desktop.
Multi thread but resource is conflict.
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