java anything memo 2

A memo for my study.

Memory area

Area for storing variable values, generated instances, history of called methods, etc. Where to store these is managed by the JVM. There are two types of memory area

--Stack --Heap

There is.

stack

Method call history, value of variable (local variable) declared in the method. When the method finishes processing, that information is removed from the stack.

heap

An instance generated from a class. When the instance is no longer referenced by any variable (change reference, assign null) In addition, it is automatically released by the garbage collection of the JVM.

thread

There are the following two types.

--Single thread

Create multithreading

There are two methods

--Create a new class that inherits the Thread class --Create a new class that implements the Runnable interface.

Make with Thread class

Create an instance of a class that inherits the Thread class Call the start method of that instance.

It's the start method that executes, In the subclass that inherits the Thread class, Override the run method of Thread class.

The run method is executed via the start method. Results are not always the same and change each time they are run (sometimes they don't)

class MyTread extends Thread{
    //NOTE: The level cannot be lowered below the access modifier defined in the superclass.
    //You can't reduce the visibility of methods inherited from Thread
    public void run() {
        for(int i = 0; i < 5; i++) {
            System.out.println("MyTread.run:"+i);
        }
    }
}

public class SampleProgram{
    public static void main(String[] args) {
        MyTread mt = new MyTread();
        mt.start();

        for(int i = 0; i < 5; i++) {
            System.out.println("main:"+i);
        }
    }
}

//result
main:0
main:1
main:2
MyTread.run:0
MyTread.run:1
MyTread.run:2
MyTread.run:3
main:3
MyTread.run:4
main:4

Create with Runnable interface

It's not much different from when it was inherited and made.

class MyTread implements Runnable{
    public void run() {
        for(int i = 0; i < 5; i++) {
            System.out.println("MyTread.run:"+i);
        }
    }
}

public class SampleProgram{
    public static void main(String[] args) {
        MyTread mt = new MyTread();
        Thread t = new Thread(mt);
        t.start();

        for(int i = 0; i < 5; i++) {
            System.out.println("main:"+i);
        }
    }
}

Thread.sleep (milliseconds (= 1/1000 second))

Stops thread processing for a certain period of time. The unit is milliseconds. 1000: 1 second 2000: 2 seconds

In microseconds 1000000: 1 second

Since the Thread.sleep method can throw an Exception of type InterruptedException I have to catch it.

public class SampleProgram{
    public static void main(String[] args) {

        for(int i = 0; i < 5; i++) {
            try {
                Thread.sleep(1000);
            }catch(InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("main:"+i);
        }
    }
}

//I tried it with the one that implemented the Runnable interface
class MyTread implements Runnable {
    public void run() {
        for(int i = 0; i < 5; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                //TODO auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("MyTread.run:"+i);
        }
    }
}

public class SampleProgram{
    public static void main(String[] args) {
        MyTread mt = new MyTread();
        Thread t = new Thread(mt);
        t.start();

        for(int i = 0; i < 5; i++) {
            System.out.println("main:"+i);
        }
    }
}

join()

You can wait for the thread to process.

Since the join method can throw an Exception of type InterruptedException I have to catch it.

After all the processing of the MyTread class is completed, the main processing is executed.

class MyTread implements Runnable {
    public void run() {
        for(int i = 0; i < 5; i++) {
            System.out.println("MyTread.run:"+i);
        }
    }
}

public class SampleProgram{
    //Now let's throws.
    public static void main(String[] args) throws InterruptedException {
        MyTread mt = new MyTread();
        Thread t = new Thread(mt);
        t.start();

        t.join();
        for(int i = 0; i < 5; i++) {
            System.out.println("main:"+i);
        }
    }
}

Stop the thread

When the processing of the run method is terminated, the processing of that thread is terminated. Hmm ... let's leave it for now.

Synchronize.

When running in multiple threads, if multiple threads share the same variable value Inconsistencies may occur.

The following is a program whose total amount will be 1000000 yen

class Bank{
    static int money = 0;
    static void addOneYen() {
        money++;
    }
}
class Customer extends Thread{
    public void run() {
        for(int i = 0; i < 10000; i++) {
            Bank.addOneYen();
        }
    }
}
public class MultiThreadEx {
    public static void main(String[] args) {
        Customer[] customers = new Customer[100];
        for(int i = 0; i < 100; i++) {
            customers[i] = new Customer();
            customers[i].start();
        }

        for(int i = 0; i < 100; i++) {
            try {
                customers[i].join();
            }catch(InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Bank.money["+Bank.money+"]");
    }
}

//result
Bank.money[628887]

Because there is no consistency between each threat at the timing of referencing / updating the current amount. The total amount goes wrong. In such a case, add "synchronized" before the addOneYen method.

    static synchronized void addOneYen() {
        money++;
    }

If you prefix the method with synchronized, you can only execute one thread at a time. When one threat is processing, the other threat waits until its turn.

Recommended Posts

java anything memo
java anything memo 2
Java memo
Java Silver memo
java, maven memo
Java SE 7 memo
Java specification memo
Java pattern memo
java basic knowledge memo
Java learning memo (method)
[Java ~ Method ~] Study memo (5)
java se 8 programmer Ⅰ memo
Java paid private memo
[Java ~ Array ~] Study memo 4
Java learning memo (basic)
java lambda expression memo
(Memo) Java for statement
Java lambda expression [memo]
Java learning memo (interface)
[Java] Implicit inheritance memo
Java learning memo (inheritance)
java competitive programming memo
[Memo] Java Linked List
Java (WebSphere Application Server) memo [1]
[Java] Variable name naming memo
Java memo (standard class) substring
Java learning memo (data type)
Java memo (standard class) length
Java Silver Study Method Memo
[Java ~ Boolean value ~] Study memo (2)
Create a java method [Memo] [java11]
Java Silver exam preparation memo
Java learning memo (logical operator)
Java
Java learning memo (abstract class)
[Java] Date Related Term Memo
Java study memo 2 with Progate
Java
What are Java metrics? _Memo_20200818
Java HashMap, entrySet [Personal memo]
[Eclipse Java] Development environment setting memo
Java learning memo (creating an array)
Personal memo: Metaprogramming with Java reflection
JCA (Java Cryptography Architecture) Usage Memo
[Study session memo] Java Day Tokyo 2017
Java learning memo (while statement, do-while statement)
From Java to VB.NET-Writing Contrast Memo-
Java beginner's stumbling block [memo writing]
[Java] Processing time measurement method memo
I tried using Java memo LocalDate
Integer memo
Java learning (0)
Studying Java ―― 3
[Java] array
[Java] Annotation
[Java] Module
Java array
Java tips, tips
(Learning memo) Java Level 2 measures: Question range
Java methods
Java method