Let's do the same thing in Java as last time.
long.java
public class Main {
private static final int REPEAT = 500000000;
private static long a = 0;
public static void main(String[] args) throws InterruptedException{
Thread th1 = new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0;i <REPEAT; i++){
a = 1;
check();
}
}
});
Thread th2 = new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0;i <REPEAT; i++){
a = -1;
check();
}
}
});
th1.start();
th2.start();
th1.join();
th2.join();
System.out.println("FINISHED!");
}
private static void check(){
if(a != 1 && a != -1){
System.out.println("LONG VALUE HAS BROKEN!");
}
}
}
Not exclusive control, but there is a volatile modifier to solve a similar problem in Java
private volatile static long a = 0;
Then the problem disappears.
volatile has the property of "always looking at the latest value when referencing a value". Roughly speaking, volatile assignments and references behave as if they were locked.
But this is not safe, so I use Atomic Long.
Atomic: Atomic operation. It means that when performing an operation, others cannot interrupt the operation.
private static AtomicLong a = new AtomicLong(0)
Quote: http://d.hatena.ne.jp/cero-t/20120830/1346267076
A synchronized block can be used for exclusive control in Java.
synchronized
public class Main {
private static final int REPEAT = 500000000;
private static Long a = new Long(0);
public static void main(String[] args) throws InterruptedException{
Thread th1 = new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0;i <REPEAT; i++){
synchronized (a){
a = new Long(1);
check();
}
}
}
});
Thread th2 = new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0;i <REPEAT; i++){
synchronized (a) {
a = new Long(-1);
check();
}
}
}
});
th1.start();
th2.start();
th1.join();
th2.join();
System.out.println("FINISHED!");
}
private static void check(){
if(a != 1 && a != -1){
System.out.println("LONG VALUE HAS BROKEN!");
}
}
}
Stream # parallel can be used for parallel processing in Java.
parallel
public class Main {
public static void main(String[] args) {
// write your code here
IntStream.range(1,10).parallel().forEach(System.out::println);
}
}
Recommended Posts