Created
August 24, 2014 10:41
-
-
Save aiya000/fe40861f07b8e4cfa89e to your computer and use it in GitHub Desktop.
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.ConcurrentMap; | |
import java.util.concurrent.ConcurrentHashMap; | |
public class Basics { | |
public static void main(String[] args){ | |
new Basics().main(); | |
} | |
public void main(){ /*{{{*/ | |
// 他スレッドから割り込みを受けないMap | |
System.out.println("Take unsafe {{{"); | |
this.unsafe(); | |
System.out.println("}}}"); | |
System.out.println("Take safe {{{"); | |
this.safe(); | |
System.out.println("}}}"); | |
} /*}}}*/ | |
private ConcurrentMap<String,Integer> safeMap; | |
public void unsafe(){ /*{{{*/ | |
this.safeMap = new ConcurrentHashMap<>(); | |
safeMap.put("a", 10); | |
Runnable jamming0 = () -> { | |
int sum = safeMap.get("a"); | |
for(int i=0; i<100; i++){ | |
sum += i; | |
safeMap.replace("a", sum); | |
System.out.println(i + ":" + safeMap.get("a")); | |
} | |
}; | |
Thread tx[] = { | |
new Thread(jamming0), | |
new Thread(jamming0) | |
}; | |
for(Thread t : tx) | |
t.start(); | |
try{ | |
tx[0].join(); | |
tx[1].join(); | |
}catch(InterruptedException e){ | |
e.printStackTrace(); | |
} | |
int sum = 10; | |
for(int i=0; i<200; i++, sum+=i); | |
System.out.println("Is " + sum + " ?"); | |
} /*}}}*/ | |
public void safe(){ /*{{{*/ | |
this.safeMap = new ConcurrentHashMap<>(); | |
safeMap.put("a", 10); | |
Runnable jamming0 = () -> { | |
int sum = safeMap.get("a"); | |
for(int i=0; i<100; i++){ | |
sum += i; | |
safeMap.putIfAbsent("a", sum); | |
System.out.println(i + ":" + safeMap.get("a")); | |
} | |
}; | |
Thread tx[] = { | |
new Thread(jamming0, "A"), | |
new Thread(jamming0, "B") | |
}; | |
for(Thread t : tx) | |
t.start(); | |
try{ | |
tx[0].join(); | |
tx[1].join(); | |
}catch(InterruptedException e){ | |
e.printStackTrace(); | |
} | |
int sum = 10; | |
for(int i=0; i<200; i++, sum+=i); | |
System.out.println("Is " + sum + " ?"); | |
} /*}}}*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment