Parallel and parallel processing in various languages (Java edition)

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

Parallel and parallel processing in various languages (Java edition)
Measured parallel processing in Java
Various threads in java
Java random, various processing
Parallel execution in Java
Variadic arguments in various languages
Encoding and Decoding example in Java
Date processing in Java (LocalDate: Initialization)
[Java] Loop processing and multiplication table
StringBuffer and StringBuilder Class in Java
Understanding equals and hashCode in Java
About file copy processing in Java
[Java] Exception types and basic processing
Hello world in Java and Gradle
Web application structure by Java and processing flow in the presentation layer
Difference between final and Immutable in Java
[Java] for Each and sorted in Lambda
Various things like bit flags in Java
Summary of root classes in various languages
Arrylist and linked list difference in java
Program PDF headers and footers in Java
Learn Flyweight patterns and ConcurrentHashMap in Java
Java Direction in C ++ Design and Evolution
Java to C and C to Java in Android Studio
Reading and writing gzip files in Java
Difference between int and Integer in Java
Discrimination of Enums in Java 7 and above
NLP4J [004] Try text analysis using natural language processing and parsing statistical processing in Java
[Java] Various methods to acquire the value stored in List by iterative processing
NLP4J [003] Try text analysis using natural language processing and part-speech statistical processing in Java
Effective Java 3rd Edition Chapter 6 enums and annotations
Regarding the transient modifier and serialization in Java
Create barcodes and QR codes in Java PDF
Detect similar videos in Java and OpenCV rev.2
Vulnerabilities and Countermeasures in Important Processing (Purchase Processing) (CSRF)
Effective Java 3rd Edition Chapter 4 Classes and Interfaces
Difference between next () and nextLine () in Java Scanner
Differences in writing Java, C # and Javascript classes
Organized memo in the head (Java --instance edition)
Effective Java 3rd Edition Chapter 7 Lambda and Streams
[Processing x Java] Data type and object-oriented programming
JAVA: Realizes generation and scanning of various barcodes
Capture and save from selenium installation in Java
Detect similar videos in Java and OpenCV rev.3
Add, read, and delete Excel comments in Java
Check static and public behavior in Java methods
[Java] Understand in 10 minutes! Associative array and HashMap
Basics of threads and Callable in Java [Beginner]
Introducing NLP4J-[000] Natural Language Processing Index in Java
Distinguish between positive and negative numbers in Java
Java adds and removes watermarks in word documents
Detect similar videos in Java and OpenCV rev.1
Represents "next day" and "previous day" in Java / Android
Questions in java exception handling throw and try-catch
Upload and download notes in java on S3
Encrypt / decrypt with AES256 in PHP and Java
Generate OffsetDateTime from Clock and LocalDateTime in Java
Partization in Java
Streams and parallel streams
[Java] How to get the key and value stored in Map by iterative processing
Changes in Java 11